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?
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.
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.
WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.
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.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With