【发布时间】:2011-10-06 22:26:01
【问题描述】:
我正在寻找一种简单的方法来让线程休眠并唤醒它。线程在后台无限循环运行,有时会做一些工作,有时只是运行。我发现 Sleep() 没有对应的 Wait() 并且使用 Interrupt() 唤醒线程会导致异常。显然,睡眠线程不应该被打扰。
因为我知道作品什么时候出现,所以告诉线程似乎是个好主意,而不是让它一遍又一遍地检查。
如何将线程置于“较轻的睡眠”状态,以便能够每秒单独唤醒或根据其他线程的命令唤醒?
//Thread to put to sleep and wake (thread1)
while (true)
{
if (thereIsWork)
{ DoWork(); }
//put thread to sleep in a way that other threads can wake it, and it wakes alone after some time (eg. 1000 ms)
// Thread.Sleep(1000); //nice, but not working as desired
}
-
//Other thread:
thereIsWork = true;
//thread1.Wake(); //Not existing
【问题讨论】:
-
使用监控对象。此处描述:stackoverflow.com/questions/209281/…
标签: c# multithreading thread-sleep