Task.Delay vs DispatcherTimer?

倾然丶 夕夏残阳落幕 提交于 2019-12-08 15:33:14

问题


I'm considering use Task.Delay() for a non-stop timer, because it's more simple and readable.

As I'm new to .NET, I see no significant difference between the two codes. Can you show me the difference (if there is any) between them?

// 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
    }

vs

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

回答1:


There are two major differences:

  1. The Task.Delay approach will delay the specified amount of time between cycles, while the DispatcherTimer approach will start a new cycle on the specified cycle time.
  2. Task.Delay is more portable, since it does not depend on a type tied to a specific UI.


来源:https://stackoverflow.com/questions/21071165/task-delay-vs-dispatchertimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!