From the following test we can see the current version of framework guarantees the output order is the same that of as the input tasks.
async Task<string> GetString1()
{
await Task.Delay(2000);
return "1";
}
async Task<string> GetString2()
{
await Task.Delay(1000);
return "2";
}
var results = await Task.WhenAll(GetString1(), GetString2());
//now we have results[0] == "1" results[1] == "2"
However, from the documentation I can't find anything about this behavior, which means it's not document-guaranteed. From the opinions of answers in this question:
Do I need to put "order flags" in the output? e.g. change the example code into following:
class OrderTaskResult<T>
{
public OrderTaskResult(int order, T value)
{
this.Order = order;
this.Value = value;
}
public int Order { get; private set; }
public T Value { get; private set; }
}
async Task<OrderTaskResult<string>> GetString1()
{
await Task.Delay(2000);
return new OrderTaskResult<string>(1, "1");
}
WhenAll can run a bunch of async methods in parallel and returns when every one finished.
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.
WhenAll method is used to create a task that will complete if and only if all the other tasks have completed. If we are using Task. WhenAll we will get a task object that isn't complete. However, it will not block but will allow the program to execute.
WhenAll has designed to handle concurrent I/O bound Tasks with higher scalability as it uses asynchronous non-blocking way to share threads to handle concurrent requests.
You're looking at the documentation for the wrong overload.
If you look at the overload that actually returns the results, you'll see:
The
Task<TResult>.Result
property of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided
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