Search code examples
c#task-parallel-libraryasync-await

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?


Solution

  • 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()));