C # tasks run before Task.WhenAll

Why tasksis running up Task.WhenAll??

If you see here, from the code snippet below, you should print first Console.WriteLine("This should be written first..");, because I have awaitingtasks below it.

But if you see the result of the output, the result of the method tasksis printed before the above statement. Ideally, the task method should be performed when I awaitgive them, but it seems that the task methods are executed when they are added to the task list. Why is this so?

Could you tell me why this is happening?

The code:

public static async Task Test()
{
    var tasks = new List<Task>();

    tasks.Add(PrintNumber(1));
    tasks.Add(PrintNumber(2));
    tasks.Add(PrintNumber(3));

    Console.WriteLine("This should be written first..");

    // This should be printed last..
    await Task.WhenAll(tasks);
}

public static async Task PrintNumber(int number)
{
    await Task.FromResult(0);

    Console.WriteLine(number);
}

Output

enter image description here

+4
source share
4 answers

async, "" . , (, , ), await. , Task.WhenAll.

, , PrintNumber async, , Task.FromResult. ( , ) . Task.FromResult, , , .

+8

( Task.FromResult, . , , .

await Task.Yield();

, .

+4

Task.FromResultwill not exit, and the task will be executed in the same thread. To achieve what you want, you can do this:

public static async Task Test()
{
    var tasks = new List<Task>();

    tasks.Add(PrintNumber(1));
    tasks.Add(PrintNumber(2));
    tasks.Add(PrintNumber(3));

    Console.WriteLine("This should be written first..");

    // This should be printed last..
    await Task.WhenAll(tasks);
}

public static async Task PrintNumber(int number)
{
    await Task.Yield();

    Console.WriteLine(number);
}
+2
source

If you want Tasktasks to start after something else, the easiest way is to write your code.

public static async Task Test()
{
    Console.WriteLine("This should be written first..");

    // These should be printed last..
    await Task.WhenAll(new[]
        {
            PrintNumber(1),
            PrintNumber(2),
            PrintNumber(3)
        });
}

following your comment.

So, we have some functions,

async Task<Customer> GetRawCustomer()
{
    ...
}

async Task<string> GetCity(Customer customer)
{
    ...
}

async Task<string> GetZipCode(Customer customer)
{
    ...
}

We could use them like that

var rawCustomer = await GetRawCustomer();

var populationWork = new List<Task>();
Task<string> getCity;
if (string.IsNullOrWhiteSpace(rawCustomer.City))
{
    getCity = GetCity(rawCustomer);
    populationWork.Add(getCity);
}

Task<string> getZipCode;
if (string.IsNullOrWhiteSpace(rawCustomer.City))
{
    getZipCode = GetZipCode(rawCustomer);
    populationWork.Add(getZipCode);
}

...

await Task.WhenAll(populationWork);

if (getCity != null)
    rawCustomer.City = getCity.Result;

if (getZipCode != null)
    rawCustomer.ZipCode = getZipCode.Result;
+2
source

All Articles