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 )
            break;
    }
    
    // Continue processing
}

The token's waithandle is signaled when you cancel its CancellationTokenSource. The WaitOne will return true because the Wait was signaled (read: cancelled) before the timeout occured.

Nice.

Comments

Thomas Levesque said…
I was about to blog about how to cancel a sleep when I found your solution, which is much more elegant than the one I had in mind... well done.

(btw, the captcha on your blog is very annoying... I'm having a hard time proving that I'm human!)
Frode said…
Thanks Thomas! ...i'll see if I can fix the captcha :)
Anonymous said…
Interesting blog.

However I would like to mention that comparing a bool type agaisnt true/false does not make much sense and should not be used.

Eg. Instead of writing:
If (someCondition == true)

You should write just:
If (someCondition)

Cheers
Anonymous said…
@ThomasLevesque Not only that, but it avoids that bit of nastyness that occurs with the "ThreadInterruptedException" whenever you do cancel a sleep state.
Sumit Sood said…
Thanks Frode! This was very useful. I was struggling to find better solution to handle cancellation with Sleep.
Janu said…

it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points.




Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery


Popular posts from this blog

Clean code with defensive programming technique