我可以使用Task.Delay作为计时器吗?

Sha*_*run 13 c# multithreading asynchronous timer task

我想每秒执行一些代码.我现在使用的代码是:

Task.Run((作用)ExecuteSomething);

ExecuteSomething()定义如下:

 private void ExecuteSomething()
        {
            Task.Delay(1000).ContinueWith(
               t =>
               {
                   //Do something.

                   ExecuteSomething();
               });
        }
Run Code Online (Sandbox Code Playgroud)

这个方法会阻塞一个线程吗?或者我应该Timer在C#中使用class?似乎Timer还专门用于执行(?)

Fab*_*bio 18

Task.DelayTimer内部使用

使用Task.Delay它可以使您的代码比使用更清晰Timer.并且使用async-await不会阻止当前线程(通常是UI).

public async Task ExecuteEverySecond(Action execute)
{
    while(true)
    {
        execute();
        await Task.Delay(1000);
    }
}
Run Code Online (Sandbox Code Playgroud)

源代码:Task.Delay

// on line 5893
// ... and create our timer and make sure that it stays rooted.
if (millisecondsDelay != Timeout.Infinite) // no need to create the timer if it's an infinite timeout
{
    promise.Timer = new Timer(state => ((DelayPromise)state).Complete(), promise, millisecondsDelay, Timeout.Infinite);
    promise.Timer.KeepRootedWhileScheduled();
}

// ...
Run Code Online (Sandbox Code Playgroud)


Eni*_*ity 5

Microsoft的Reactive Framework为此非常理想。只需NuGet“ System.Reactive”即可获取这些位。然后,您可以执行以下操作:

IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0))
        .Subscribe(x => execute());
Run Code Online (Sandbox Code Playgroud)

当您想停止订阅时,只需致电即可subscription.Dispose()。最重要的是,Reactive Framework可以提供比Task或Basic计时器更多的功能。

  • 在我的情况下使用 Rx 是否比使用 Task.Delay 有任何特定优势?只是想知道是否值得为此目的包含软件包。反正投了赞成票。 (2认同)