Use CancellationToken to Make Responsive Thread.Sleep() Wait

Using a time delay based on a Thread.Sleep() is truly easy.

// Example: https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.sleep?view=netframework-4.8
class Example
{
    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Sleep for 2 seconds.");
            Thread.Sleep(2000);
        }

        Console.WriteLine("Main thread exits.");
    }
}

However, if you need a pause inside code that is using a CancellationToken, be aware that if the CancellationTokenSource calls the Cancel() method, Thread.Sleep() will ignore the request.

CancellationToken Aware Sleep()

In the example below, we get the WaitHandle from the token and pass in delay time (in milliseconds). If the token is cancelled before the wait interval is up, the method will exit immediately. If we wanted, we could examine the returned WaitHandle and determine if the method exited because of timeout or the token was cancelled. In this case, I don’t care since I will test it at the top of the loop.

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;

// Do work then pause. Repeat until cancelled.
while (!token.IsCancellationRequested)
{ 
    // Do work.
    ...

    // Pause for 60 seconds before doing more work OR until token cancelled.
    token.WaitHandle.WaitOne(60000);
}