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

后端 未结 5 2059
终归单人心
终归单人心 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:06

    I just blogged about it here:

    CancellationToken and Thread.Sleep

    in Short:

    var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));
    

    In your context:

    void MyFunc (CancellationToken ct)
    {
       //... 
       // simulate some long lasting operation that should be cancelable 
       var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
    }
    

提交回复
热议问题