Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda