如何异步等待 x 秒然后执行某些操作? [英] How to asynchronously wait for x seconds and execute something then?
问题描述
我知道有 Thread.Sleep
和 System.Windows.Forms.Timer
和 Monitor.Wait
在 C# 和 Windows 窗体中.我似乎无法弄清楚如何在不锁定线程的情况下等待 X 秒然后做其他事情.
I know there is Thread.Sleep
and System.Windows.Forms.Timer
and Monitor.Wait
in C# and Windows Forms. I just can't seem to be able to figure out how to wait for X seconds and then do something else - without locking the thread.
我有一个带按钮的表单.单击按钮时,计时器应启动并等待 5 秒.在这 5 秒后,窗体上的其他一些控件变为绿色.使用 Thread.Sleep
时,整个应用程序将在 5 秒内无响应 - 那么我如何在 5 秒后做某事"?
I have a form with a button. On button click a timer shall start and wait for 5 seconds. After these 5 seconds some other control on the form is colored green. When using Thread.Sleep
, the whole application would become unresponsive for 5 seconds - so how do I just "do something after 5 seconds"?
推荐答案
(从 Ben 作为评论转录)
(transcribed from Ben as comment)
只需使用 System.Windows.Forms.Timer.将定时器设置为 5 秒,并处理 Tick 事件.当事件触发时,做这件事.
just use System.Windows.Forms.Timer. Set the timer for 5 seconds, and handle the Tick event. When the event fires, do the thing.
...并在执行工作之前禁用计时器 (IsEnabled=false) 以抑制一秒钟.
...and disable the timer (IsEnabled=false) before doing your work in oder to suppress a second.
Tick 事件可能在另一个无法修改您的 gui 的线程上执行,您可以捕获:
The Tick event may be executed on another thread that cannot modify your gui, you can catch this:
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
private void StartAsyncTimedWork()
{
myTimer.Interval = 5000;
myTimer.Tick += new EventHandler(myTimer_Tick);
myTimer.Start();
}
private void myTimer_Tick(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
/* Not on UI thread, reenter there... */
this.BeginInvoke(new EventHandler(myTimer_Tick), sender, e);
}
else
{
lock (myTimer)
{
/* only work when this is no reentry while we are already working */
if (this.myTimer.Enabled)
{
this.myTimer.Stop();
this.doMyDelayedWork();
this.myTimer.Start(); /* optionally restart for periodic work */
}
}
}
}
<小时>
只是为了完整性:使用 async/await,可以很容易地延迟执行某些事情(一次,永远不要重复调用):
Just for completeness: with async/await, one can delay execute something very easy (one shot, never repeat the invocation):
private async Task delayedWork()
{
await Task.Delay(5000);
this.doMyDelayedWork();
}
//This could be a button click event handler or the like */
private void StartAsyncTimedWork()
{
Task ignoredAwaitableResult = this.delayedWork();
}
有关更多信息,请参阅 MSDN 中的异步和等待".
For more, see "async and await" in MSDN.
这篇关于如何异步等待 x 秒然后执行某些操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!