What\'s the best way to sleep a certain amount of time, but be able to be interrupted by a IsCancellationRequested
from a CancellationToken
?
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);
}
}