如何异步等待x秒和执行的东西呢? [英] How to asynchronously wait for x seconds and execute something then?
问题描述
我知道有 Thread.sleep代码
和 System.Windows.Forms.Timer
和<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx\"><$c$c>Monitor.Wait$c$c>在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"?
推荐答案
(从本为注释转录)
只是使用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.
...和做在奥得你的工作燮preSS前一秒钟禁止定时器(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 */
}
}
}
}
只是为了完整性:与异步/的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屋!