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

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

    The CancellationToken.WaitHandle can throw an exception when accessed after the CancellationTokenSource has been disposed:

    ObjectDisposedException: The CancellationTokenSource has been disposed.

    In some cases, especially when linked cancellation sources are being manually disposed (as they should be), this can be a nuisance.

    This extension method allows 'safe cancellation waiting'; however, it should be used on conjunction with checks to, and proper flagging of, the cancellation token's state and/or usage of the return value. This is because it suppresses exceptions access the WaitHandle and may return faster than expected.

    internal static class CancellationTokenExtensions
    {
        /// 
        /// Wait up to a given duration for a token to be cancelled.
        /// Returns true if the token was cancelled within the duration
        /// or the underlying cancellation token source has been disposed.
        /// 
        public static bool WaitForCancellation(this CancellationToken token, TimeSpan duration)
        {
            WaitHandle handle;
            try
            {
                handle = token.WaitHandle;
            }
            catch
            {
                // eg. CancellationTokenSource is disposed
                return true;
            }
    
            return handle.WaitOne(duration);
        }
    }
    

提交回复
热议问题