Task.Delay与DispatcherTimer? [英] Task.Delay vs DispatcherTimer?
本文介绍了Task.Delay与DispatcherTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在考虑将Task.Delay()
用于不间断计时器,因为它更简单易读.
I'm considering use Task.Delay()
for a non-stop timer, because it's more simple and readable.
由于我是.NET的新手,所以我认为这两个代码之间没有显着差异.您能告诉我它们之间的区别(如果有)吗?
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
}
}
推荐答案
有两个主要区别:
-
Task.Delay
方法将在个循环之间延迟指定的时间,而DispatcherTimer
方法将在指定的循环时间开始一个新的循环. -
Task.Delay
具有更高的可移植性,因为它不依赖于绑定到特定UI的类型.
- The
Task.Delay
approach will delay the specified amount of time between cycles, while theDispatcherTimer
approach will start a new cycle on the specified cycle time. Task.Delay
is more portable, since it does not depend on a type tied to a specific UI.
这篇关于Task.Delay与DispatcherTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文