Learner
Learner

Reputation: 1542

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..

Upvotes: 21

Views: 10465

Answers (1)

dtb
dtb

Reputation: 217293

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
}

Upvotes: 30

Related Questions