我目前正在开发一个应用程序,我想实现一个时间延迟。我不想使用System.Threading.Thread.Sleep(x);当我读到这段代码时,线程会停止(UI冻结)
我现在写的代码是:
public void atimerdelay()
{
lblStat.Text = "In the timer";
System.Timers.Timer timedelay;
timedelay = new System.Timers.Timer(5000);
timedelay.Enabled = true;
timedelay.Start();
}我知道atimerdelay()确实会被调用(使用lblStat),但它们不会有5秒的延迟。我读过http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx,但我不明白为什么上面的代码不能工作。
其他信息-(为Hamlet Hakobyan添加)
该应用程序是一个“卡片检查器”应用程序(大学项目-没有使用或存储任何实际信息)。一旦用户填写完所有相关的表格并点击“检查”,验证方法列表就会被调用。在调用其中任何一个之前,将执行ping以确保计算机上存在有效的互联网连接。我想在ping和验证开始之间添加一个小小的延迟。
发布于 2013-01-31 20:09:03
这样如何:
await Task.Delay(5000)?它不会阻塞UI线程,而且看起来很不错!
发布于 2013-01-31 20:08:18
我永远不会忘记this wonderful snippet的。它适用于Windows Form应用程序,并且比创建Timer要轻量级得多。
发布于 2013-01-31 20:11:08
您可以使用System.Timers.Timer在经过一段时间间隔后触发事件。它们对于简单地延迟执行并不有用。
如果您在代码中添加了:timedelay.Elapsed += delayedFunction;,那么delayedFunction将在5秒后被调用。
https://stackoverflow.com/questions/14625427
复制相似问题