Retrieving Return Values ​​from Task.WhenAll

Hopefully pretty simple here. I have a set of objects, each of which has an async method that I want to call and collect values. I would like them to run in parallel. What I would like to achieve can be summarized in one broken line of code:

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

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

+6
source share
1 answer

If the tasks you expect 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 the following results:

 var myCollection = new List<Test>(); myCollection.Add(new Test()); IEnumerable<TestResult> results = await Task.WhenAll(myCollection.Select(v => v.TestAsync())); 
+10
source

Source: https://habr.com/ru/post/977968/


All Articles