Is there a way to wake a sleeping thread?

后端 未结 7 1757
伪装坚强ぢ
伪装坚强ぢ 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:40

    Based on Ilia's suggestion:

    t1 = new Thread(() =>
        {
         while (keepRunning) {
             try {
                 DoWork();
                 Thread.Sleep(all_night_long);
                 }
             catch (ThreadInterruptedException) { }
             }
        });
    t1.Start();
    

    and...

    public void WakeUp()
    {
       t1.Interrupt();
    }
    
    public void StopRunningImmediately()
    {
       keepRunning = false;
       WakeUp(); //immediately
    }
    

    This solution is crude, as there may be other reasons why the ThreadInterruptedException is thrown.

提交回复
热议问题