有没有办法唤醒睡眠线程?

spi*_*pig 13 c# multithreading sleep

有没有办法在C#中唤醒一个睡眠线程?那么,让它睡了很长时间并在你想要处理工作时将其唤醒?

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)


JSB*_*ոգչ 5

如果你的线程在一个调用中Sleep,那么(通常)没有一种方法来唤醒它.(我所知道的唯一例外是Java,它允许在某些其他线程调用时提前结束休眠thread.interrupt().)

你正在谈论的模式似乎要求一个事件:线程包含一个循环,在它的顶部等待一个事件被触发.如果事件当前未设置,则线程"休眠",直到某个其他线程触发该事件.此时,睡眠线程唤醒并继续其工作,直到下一次通过循环时它休眠等待另一个事件.


ILI*_*DNO 5

C#中其实有一个thread.Interrupt()方法。虽然接受的答案确实描述了您在您的情况下可能需要的良好模式,但我来到这个问题寻找 Thread.Interrupt 所以我把它放在这里。