How to “sleep” until timeout or cancellation is requested in .NET 4.0

后端 未结 5 2040
终归单人心
终归单人心 2020-12-13 12:24

What\'s the best way to sleep a certain amount of time, but be able to be interrupted by a IsCancellationRequested from a CancellationToken?

<
5条回答
  •  温柔的废话
    2020-12-13 13:07

    The best solution I found so far is:

    void MyFunc(CancellationToken ct)
    {
      //...
      var timedOut = WaitHandle.WaitAny(new[] { ct.WaitHandle }, TimeSpan.FromMilliseconds(2000)) == WaitHandle.WaitTimeout;
      var cancelled = ! timedOut;
    }
    

    UPDATE:

    The best solution so far is the accepted answer.

提交回复
热议问题