等待一段时间而不阻塞主线程 [英] Wait for a while without blocking main thread
本文介绍了等待一段时间而不阻塞主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的方法等待大约500毫秒,然后检查某些标志是否已更改.如何在不阻止应用程序其余部分的情况下完成此任务?
I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?
推荐答案
Thread.Sleep(500)
将强制当前线程等待500ms.它可以工作,但是如果整个应用程序都在一个线程上运行,那不是您想要的.
Thread.Sleep(500)
will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.
在这种情况下,您将要使用Timer
,如下所示:
In that case, you'll want to use a Timer
, like so:
using System.Timers;
void Main()
{
Timer t = new Timer();
t.Interval = 500; // In milliseconds
t.AutoReset = false; // Stops it from repeating
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello, world!");
}
如果希望计时器重复进行,则可以将AutoReset
设置为true(或者根本不设置).
You can set AutoReset
to true (or not set it at all) if you want the timer to repeat itself.
这篇关于等待一段时间而不阻塞主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文