Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is result of Task.WhenAll order guaranteed?

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");
}
like image 659
Cheng Chen Avatar asked Apr 06 '16 02:04

Cheng Chen


People also ask

What does WhenAll return?

WhenAll can run a bunch of async methods in parallel and returns when every one finished.

How does task WhenAll work?

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?

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.

Is task WhenAll concurrent?

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.


1 Answers

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

like image 172
SLaks Avatar answered Nov 04 '22 07:11

SLaks