Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the CancellationToken with Tasks.WaitAll()

I'm wondering how to use the Task.WaitAll overloads that take a CancellationToken as an argument, e.g. https://msdn.microsoft.com/en-us/library/dd321573%28v=vs.110%29.aspx

The documentation says the CancellationToken argument is "A CancellationToken to observe while waiting for the tasks to complete."

Since Task.WaitAll is a blocking operation, how could you possibly "observe" it during that operation? Furthermore, it says "The cancellationToken argument is used to cancel the wait operation. If it is canceled, the Wait returns false." but then it also says elsewhere that a OperationCanceledException is thrown when the CancellationToken is cancelled, meaning Task.WaitAll doesn't return true or false.

I'm either missing something really simple, or something is wrong with the documentation. Either way, I'm thoroughly confused. My ultimate goal is to be able to wait for multiple tasks to finish or to cancel them gracefully (via the proper use of CancellationToken) if they don't finish within a certain period of time.

This is related to my post here, but this time, I'm writing the async code and can observe the cancellation tokens.

like image 404
rory.ap Avatar asked Sep 28 '22 21:09

rory.ap


1 Answers

Since Task.WaitAll is a blocking operation, how could you possibly "observe" it during that operation?

You're not the one who observes it; it's the Task.WaitAll method that does.

Furthermore, it says "The cancellationToken argument is used to cancel the wait operation. If it is canceled, the Wait returns false." but then it also says elsewhere that a OperationCanceledException is thrown when the CancellationToken is cancelled, meaning Task.WaitAll doesn't return true or false.

It seems to be a mistake in the documentation. It returns false if the specified timeout elapses before the tasks complete or the wait is canceled.

Who cancels it?

Typically, some code running on another thread, since the current thread is already busy waiting for the tasks to complete. Or you could have called CancellationTokenSource.CancelAfter to specify a timeout after which the token is canceled.

like image 101
Thomas Levesque Avatar answered Oct 05 '22 07:10

Thomas Levesque