Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max tasks for Task.WaitAny?

I'm creating a system which will spawn a lot of worker tasks and in some point of my app I'm doing a Task.WaitAny to retrieve the first finished task.

My concern is about how many tasks can I send to WaitAny, I know WaitHandle's WaitAny/All only can support up to 64 wait handles and I'm not sure if the underlying mechanism on Task.WaitAny uses internally wait handles to wait for a finished task and thus these limits apply to them.

Is there any limit to how many tasks can be passed to Task.WaitAny like with WaitHandles or there's no limit?

Cheers.

like image 367
Gusman Avatar asked Jan 06 '23 10:01

Gusman


2 Answers

From what I see, it internally works by chaining a continuation to all the tasks: http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/TaskFactory.cs,db51a91904616672
(with internal optimizations, as well as some code to handle the racing condition when multiple tasks end at once)

Therefore, the limitations on WaitHandles shouldn't apply here.

like image 85
Kevin Gosse Avatar answered Jan 13 '23 21:01

Kevin Gosse


Internally Task.WaitAny is calling TaskFactory.CommonCWAnyLogic which is scheduling a continuation on each task you pass in, that continuation marks which index in the array it was and allows the task to complete. It uses the inernal class CompleteOnInvokePromise which could be thought of as kind of a specialized TaskCompletionSource.

Because it is using task continuations and not wait handles the wait handle limit should not apply.

like image 39
Scott Chamberlain Avatar answered Jan 13 '23 20:01

Scott Chamberlain