Wim*_*nen 16
可以使用AutoResetEvent对象(或其他WaitHandle实现)进行休眠,直到收到来自另一个线程的信号:
// launch a calculation thread
var waitHandle = new AutoResetEvent(false);
int result;
var calculationThread = new Thread(
delegate
{
// this code will run on the calculation thread
result = FactorSomeLargeNumber();
waitHandle.Set();
});
calculationThread.Start();
// now that the other thread is launched, we can do something else.
DoOtherStuff();
// we've run out of other stuff to do, so sleep until calculation thread finishes
waitHandle.WaitOne();
Run Code Online (Sandbox Code Playgroud)
如果你的线程在一个调用中Sleep,那么(通常)没有一种方法来唤醒它.(我所知道的唯一例外是Java,它允许在某些其他线程调用时提前结束休眠thread.interrupt().)
你正在谈论的模式似乎要求一个事件:线程包含一个循环,在它的顶部等待一个事件被触发.如果事件当前未设置,则线程"休眠",直到某个其他线程触发该事件.此时,睡眠线程唤醒并继续其工作,直到下一次通过循环时它休眠等待另一个事件.
| 归档时间: |
|
| 查看次数: |
22532 次 |
| 最近记录: |