Sometimes you need to wait for a cancellation token, or for a fixed amount of time.
For example, you may be implementing some sort of automatic retry with exponential backoffs, but also with the ability for a user to try to force an immediate retry.
You can use a cancellationToken, but wait for it with the WaitHandle. then either the timeout of the WaitHandle, or the Cancellation of the token can continue your code
You can play with the numbers in this code snippet to see it in action
|
1 2 3 4 5 6 7 8 9 10 |
var cancellationTokenSource = new CancellationTokenSource(); var sw = Stopwatch.StartNew(); cancellationTokenSource.CancelAfter(1000); cancellationTokenSource.Token.WaitHandle.WaitOne(3000); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.WriteLine("end"); |