CancellationToken and Thread.Sleep
I have a task that, when some condition occur, sleeps for a few seconds. Most of the time, the task does some heavy processing, so I can't use a thread timer. The problem with the sleep is that, whenever I cancel the task using the CancellationToken(Source), I have to wait for the sleep to finish before the task finishes. The Thread.Sleep doesn't have any CancellationToken parameter. while (token.IsCancellationRequested == false ) { // Initial processing if ( someCondition == true ) { // Sleep for 5 seconds Thread .Sleep(5000); } // Continue processing } The solution is quite simple - use the cancellation token's wait handle: while (token.IsCancellationRequested == false ) { // Initial processing if ( someCondition == true ) { // Sleep for 5 seconds, but exit if token is cancelled var cancelled = token.WaitHandle.WaitOne(5000); if ( cancelled )