13

我正在考虑使用Task.Delay()不间断计时器,因为它更简单易读。

由于我是 .NET 新手,因此我认为这两个代码之间没有显着差异。你能告诉我它们之间的区别(如果有的话)吗?

// Create variable at some place
DispatcherTimer timer = new DispatcherTimer();

timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += timer_Elapsed;
timer.Start();

// Function other place
void timer_Elapsed(object sender, EventArgs e)
{
    //Do stuff
    }

对比

// Every thing inside a function
async void TaskTimer()
{
    while (true)
    {
        await Task.Delay(5000);
        // Do stuff
    }
}
4

1 回答 1

8

有两个主要区别:

  1. 该方法将在周期之间Task.Delay延迟指定的时间量,而该方法将在指定的周期时间开始一个新的周期。DispatcherTimer
  2. Task.Delay更便携,因为它不依赖于绑定到特定 UI 的类型。
于 2014-01-12T05:54:43.790 回答