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.
The solution is quite simple - use the cancellation token's wait handle:
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.
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
(btw, the captcha on your blog is very annoying... I'm having a hard time proving that I'm human!)
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
Dot Net Online Course Hyderabad
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