Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
Why does storing multiple tasks in a var first and awaiting them afterwards make a difference?

Given this code... Why will Main1() take ~ 1 second but Main2() only 500 ms?

Why does it make a difference to store the Task in a variable first and awaiting then?

async Task Main1()
{
    await DoStuff(1);
    await DoStuff(2);
}

async Task Main2()
{
    var t1 = DoStuff(1);
    var t2 = DoStuff(2);
    await t1;
    await t2;
}

async Task DoStuff(int number)
{
    await Task.Delay(500);
    Console.WriteLine(number);
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

It's not about whether you store the tasks in variables, it's about when you start the tasks. In this case:

async Task Main1()
{
    await DoStuff(1); // Task 1
    await DoStuff(2); // Task 2
}

You start task 2 after you wait for task 1 to finish. Note that calling DoStuff starts the task, and await wait for it to finish.

In this case:

async Task Main2()
{
    var t1 = DoStuff(1); // Task 1
    var t2 = DoStuff(2); // Task 2
    await t1;
    await t2;
}

You start task 2 without waiting for task 1 to finish, so they are executed asynchronously.

If you did this instead:

async Task Main3()
{
    var t1 = DoStuff(1);
    await t1;
    var t2 = DoStuff(2);
    await t2;
}

You would get the same behaviour as Main1. This shows that whether or not you put the task into variables doesn't matter.

over 4 years ago · Santiago Trujillo Relatório

0

In Main1, DoStuff(2) get started only when DoStuff(1) is done. But in Main2, both t1 and t2 task start almost at same time and are handled concurrently.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda