Repository navigation
Description
Description
When there are more than two Tasks passed to Task.WhenAny, an array is allocated as a protection measure.
runtime/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs
Lines 6637 to 6640 in 6adf63b
| // Make a defensive copy, as the user may manipulate the input collection | |
| // after we return but before the WhenAny asynchronously completes. | |
| TTask[] tasksCopy = tasks.ToArray(); | |
| foreach (TTask task in tasksCopy) |
Would it be possible to use ArrayPool to eliminate this allocation in WhenAny? This could be beneficial in high-throughput async scenarios where WhenAny is called frequently, as it currently allocates a Task[] on every call with more than two tasks.
I've looked into the internals and it seems like this change could be straightforward to add — the rented array could be returned to the pool once the work is finished.
runtime/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs
Lines 2319 to 2325 in 6adf63b
| for (int i = 0; i < numTasks; i++) | |
| { | |
| TTask task = tasks[i]; | |
| if (task != null && // if an element was erroneously nulled out concurrently, just skip it; worst case is we don't remove a continuation | |
| !task.IsCompleted) task.RemoveContinuation(this); | |
| } | |
| _tasks = null; |
I'm happy to implement this change myself if the approach is considered feasible — would just appreciate approval before diving in. It may also be worth adding a dedicated fast path for exactly 3/4 tasks, similar to how 2 tasks is currently handled, to avoid the allocation entirely in that case as well.
Activity
dotnet-policy-service commentedon Apr 10, 2026
Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.
jkotas commentedon Apr 10, 2026
Have you measured the cost of this allocation vs. the total cost of the WhenAny API?
ArrayPool is not free, it can hurt overall performance when used for small short-lived allocations, and comes with safety risks associated with manually managed lifetime.
timcassell commentedon Apr 13, 2026
When necessary to avoid async allocations, I'd suggest using another library besides TPL, like ProtoPromise or UniTask. https://github.com/timcassell/CSharpAsynchronousBenchmarks
tannergooding commentedon Apr 15, 2026
As Jan calls out, we'd need perf/benchmark numbers for any change here. Ideally this would also showcase improvements to real world code.
I'd expect that adding a special path for a common number of tasks (likely 1-4, which is what we optimize in various other places including for
params) would be the better and safer approach here.unsafePtr commentedon Apr 15, 2026
Hi all! I've been on holiday and picked this up this morning. Please find the preliminary results below and the basline is the current toolchain. @jkotas there is no performance degradation even on small counts of 3/5 items. @tannergooding , agree that common number of tasks can be expanded.
Benchmark
Implementation
jkotas commentedon Apr 15, 2026
Microbenchmarks like this won't show the overall degradation caused by ArrayPool use.
unsafePtr commentedon Apr 21, 2026
Added fast path for 3/4 Tasks. #127216
Follow-up - are there scenarios where callers with large, known-stable task collections (e.g., long-lived cached arrays in a hot path) could skip the defensive copy safely? Would you consider having
public static Task<Task> WhenAny(Task[] tasks, bool copyTasks)?unsafePtr commentedon Apr 21, 2026
Closing. 2-task is the most common pattern, and the maintenance cost of adding 3- and 4-task specializations is higher than the benefit - as discussed in #127216.
Sourcegraph global regex search for direct 3-arg
Task.WhenAny(a, b, c):https://sourcegraph.com/search?q=context:global+patterntype:regexp+Task%5C.WhenAny%5C%28%5B%5E%2C%28%29%5D%2B%2C%5B%5E%2C%28%29%5D%2B%2C%5B%5E%2C%28%29%5D%2B%5C%29&patternType=regexp
Thank you for the feedback.