Gusman
Gusman

Reputation: 15161

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.

Upvotes: 4

Views: 437

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

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.

Upvotes: 4

Kevin Gosse
Kevin Gosse

Reputation: 39017

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.

Upvotes: 5

Related Questions