16

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

4

1 回答 1

24

假设您有一个ManualResetEventSlim类型的信号,并且想要等待信号被设置、操作被取消或操作超时。然后你可以使用Wait方法如下:

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

但是如果你有一个ManualResetEvent类型的信号,就没有这样的 Wait 方法。在这种情况下,您可以使用CancellationTokenWaitHandleWaitHandle.WaitAny 方法来达到相同的效果:

if (WaitHandle.WaitAny(new WaitHandle[] { signal, cancellationToken.WaitHandle },
                       TimeSpan.FromSeconds(10)) == 0)
{
    // signal set
}
else
{
    // cancelled or timeout
}
于 2012-08-26T12:02:04.763 回答