Skip to content

Add fast paths to WhenAny(IEnumerable) #38896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 11, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5472,15 +5472,15 @@ protected override void Cleanup()
/// </exception>
public static Task WhenAll(IEnumerable<Task> tasks)
{
// Take a more efficient path if tasks is actually an array
if (tasks is Task[] taskArray)
{
return WhenAll(taskArray);
}

// Skip a List allocation/copy if tasks is a collection
if (tasks is ICollection<Task> taskCollection)
{
// Take a more efficient path if tasks is actually an array
if (tasks is Task[] taskArray)
{
return WhenAll(taskArray);
}

int index = 0;
taskArray = new Task[taskCollection.Count];
foreach (Task task in tasks)
Expand Down Expand Up @@ -6080,6 +6080,25 @@ public void Invoke(Task completingTask)
/// </exception>
public static Task<Task> WhenAny(IEnumerable<Task> tasks)
{
// Skip a List allocation/copy if tasks is a collection
if (tasks is ICollection<Task> taskCollection)
{
// Take a more efficient path if tasks is actually an array
if (tasks is Task[] taskArray)
{
return WhenAny(taskArray);
}

int index = 0;
taskArray = new Task[taskCollection.Count];
foreach (Task task in tasks)
{
if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
taskArray[index++] = task;
}
return TaskFactory.CommonCWAnyLogic(taskArray);
}

if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);

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