我正在寻找一种简单的方法来让线程进入睡眠状态并唤醒它。线程在后台无限循环运行,有时会做一些工作,有时只是运行。我发现 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