Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancellation with WaitHandle

I am reading a lot on TPL and found out the ways in which we can use the cancellation mechanism. But i got stuck with WaitHandle.

If i want to cancel the task, i can define the CancellationTokenSource and pass it along with the Task and i can use ThrowIfCancellationRequested method to cancel the task.

My question is when i need to use WaitHandle for cancellation purpose, and why simple cancellation can't work in that situation?

EDIT MSDN link : http://msdn.microsoft.com/en-us/library/dd997364 .. see listening by using WaitHandle..

Just learning TPL..

Please help..

like image 831
Learner Avatar asked Aug 26 '12 11:08

Learner


People also ask

How does the cancellation token work?

The wait handle of the cancellation token will become signaled in response to a cancellation request, and the method can use the return value of the WaitAny method to determine whether it was the cancellation token that signaled. The operation can then just exit, or throw an OperationCanceledException, as appropriate.

Is CancellationTokenSource thread safe?

They are thread-safe out of the box. They can be created from different sources by combining CancellationToken s.


1 Answers

Assume you have a signal of type ManualResetEventSlim and want to wait for the signal to be set, the operation to be cancelled or the operation to time out. Then you can use the Wait method as follows:

if (signal.Wait(TimeSpan.FromSeconds(10), cancellationToken))
{
    // signal set
}
else
{
    // cancelled or timeout
}

But if you have a signal of type ManualResetEvent, there is no such Wait method. In this case, you can use the CancellationToken's WaitHandle and the WaitHandle.WaitAny method to achieve the same effect:

if (WaitHandle.WaitAny(new WaitHandle[] { signal, cancellationToken.WaitHandle },
                       TimeSpan.FromSeconds(10)) == 0)
{
    // signal set
}
else
{
    // cancelled or timeout
}
like image 186
dtb Avatar answered Sep 19 '22 13:09

dtb