Is there a way to wake a sleeping thread?

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

    Expanding Wim's answer you can also specify a timeout for the WaitHandle.WaitOne() call. So you can use instead of Thread.Sleep(). CancellationToken struct provides you with one so you can signal your tasks like this:

    string SleepAndWakeUp(string value,CancellationToken ct)
    {
        ct.WaitHandle.WaitOne(60000);
        return value;
    }
    
    void Parent()
    {
         CancellationTokenSource cts = new CancellationTokenSource();
         Task.Run(() => SleepAndWakeUp("Hello World!", cts.Token), cts.Token);
         //Do some other work here
         cts.Cancel(); //Wake up the asynch task
    }
    

提交回复
热议问题