Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return values from Task.WhenAll

Hopefully a fairly simple one here. I have a collection of objects, each of which has an async method that I want to call and collect values from. I'd like them to run in parallel. What I'd like to achieve can be summed up in one broken line of code:

IEnumerable<TestResult> results = await Task.WhenAll(myCollection.Select(v => v.TestAsync()));

I've tried various ways of writing this without success. Any thoughts?

like image 531
wwarby Avatar asked Nov 10 '14 08:11

wwarby


People also ask

What does WhenAll return?

public static Task WhenAll (params Task[] tasks); Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

Does task WhenAll block?

The call to WhenAll<TResult>(Task<TResult>[]) method does not block the calling thread. However, a call to the returned Result property does block the calling thread.

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

How do I return a task in C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.


1 Answers

If the tasks you're awaiting have a result of the same type Task.WhenAll returns an array of them. For example for this class:

public class Test
{
    public async Task<TestResult> TestAsync()
    {
        await Task.Delay(1000); // Imagine an I/O operation.
        return new TestResult();
    }
}

We get these results:

var myCollection = new List<Test>();
myCollection.Add(new Test());

IEnumerable<TestResult> results = await Task.WhenAll(myCollection.Select(v => v.TestAsync()));
like image 181
i3arnon Avatar answered Sep 18 '22 20:09

i3arnon