Is there a way to wake a sleeping thread?

后端 未结 7 1707
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 05:13

Is there a way to wake a sleeping thread in C#? So, have it sleep for either a long time and wake it when you want work processed?

相关标签:
7条回答
  • 2021-01-04 05:49

    An AutoResetEvent object (or another WaitHandle implementation) can be used to sleep until a signal from another thread is received:

    // 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();
    
    0 讨论(0)
提交回复
热议问题