Skip to content

Commit 9321d39

Browse files
authored
Add fast paths to WhenAny(IEnumerable) (#38896)
* Add fast paths to WhenAny(IEnumerable) Adds fast paths in case `tasks` is an array or an `ICollection` * Remove cast from slow path for WhenAll and WhenAny
1 parent 921db35 commit 9321d39

File tree

1 file changed

+25
-6
lines changed
  • src/libraries/System.Private.CoreLib/src/System/Threading/Tasks

1 file changed

+25
-6
lines changed

src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5469,15 +5469,15 @@ protected override void Cleanup()
54695469
/// </exception>
54705470
public static Task WhenAll(IEnumerable<Task> tasks)
54715471
{
5472-
// Take a more efficient path if tasks is actually an array
5473-
if (tasks is Task[] taskArray)
5474-
{
5475-
return WhenAll(taskArray);
5476-
}
5477-
54785472
// Skip a List allocation/copy if tasks is a collection
54795473
if (tasks is ICollection<Task> taskCollection)
54805474
{
5475+
// Take a more efficient path if tasks is actually an array
5476+
if (tasks is Task[] taskArray)
5477+
{
5478+
return WhenAll(taskArray);
5479+
}
5480+
54815481
int index = 0;
54825482
taskArray = new Task[taskCollection.Count];
54835483
foreach (Task task in tasks)
@@ -6077,6 +6077,25 @@ public void Invoke(Task completingTask)
60776077
/// </exception>
60786078
public static Task<Task> WhenAny(IEnumerable<Task> tasks)
60796079
{
6080+
// Skip a List allocation/copy if tasks is a collection
6081+
if (tasks is ICollection<Task> taskCollection)
6082+
{
6083+
// Take a more efficient path if tasks is actually an array
6084+
if (tasks is Task[] taskArray)
6085+
{
6086+
return WhenAny(taskArray);
6087+
}
6088+
6089+
int index = 0;
6090+
taskArray = new Task[taskCollection.Count];
6091+
foreach (Task task in tasks)
6092+
{
6093+
if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
6094+
taskArray[index++] = task;
6095+
}
6096+
return TaskFactory.CommonCWAnyLogic(taskArray);
6097+
}
6098+
60806099
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
60816100

60826101
// Make a defensive copy, as the user may manipulate the tasks collection

0 commit comments

Comments
 (0)