c#如何在两个函数调用之间暂停而不停止主线程



c#如何在两个函数调用之间暂停而不停止主线程

Foo();
Foo(); // i want this to run after 2 min without stopping main thread

Function Foo()
{
}

谢谢

尝试:

Task.Factory.StartNew(() => { foo(); })
    .ContinueWith(t => Thread.Sleep(2 * 60 * 1000))
    .ContinueWith(t => { Foo() });
    Task.Factory.StartNew(Foo)
                .ContinueWith(t => Task.Delay(TimeSpan.FromMinutes(2)))
                .ContinueWith(t => Foo());

请不要在线程池中休眠。从来没有

"线程池中的线程数量有限;线程池旨在有效地执行大量短任务。它们依赖于每个任务的快速完成,以便线程可以返回池并用于下一个任务。"这里

为什么是Delay ?它在内部使用DelayPromiseTimer ,这很有效,更有效

如何使用Timer:

var timer = new Timer();
timer.Interval = 120000;
timer.Tick += (s, e) =>
{
    Foo();
    timer.Stop();
}
timer.Start();

尝试生成一个新线程,如下所示:

new Thread(() => 
    {
         Foo();
         Thread.Sleep(2 * 60 * 1000);
         Foo();
    }).Start();

你可以使用Timer类

using System;
using System.Timers;
public class Timer1
{
    private static System.Timers.Timer aTimer;
    public void Foo()
    {
    }
    public static void Main()
    {
        Foo();
        // Create a timer with a two minutes interval.
        aTimer = new System.Timers.Timer(120000);
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(Foo());
        aTimer.Enabled = true;
    }
    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Foo();
    }
}

代码未经过测试。

var testtask = Task.Factory.StartNew(async () =>
    {
        Foo();
        await Task.Delay(new TimeSpan(0,0,20));
        Foo();
    });

最新更新