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

372
Visualizações
Why is this different? Async running sequentially vs parallel

Given this:

private static async Task<int> Operation1()
{
    await Task.Delay(1000);
    return 1;
}

private static async Task<int> Operation2()
{
    await Task.Delay(1000);
    return 1;
}

this is running sequentially, i.e. it takes 2 seconds (measured using Stopwatch)

var a = await Operation1();
var b = await Operation2();

var result = Operation3(a, b);

while this takes only 1 second, running things in parallel:

var taskA = Operation1();
var taskB = Operation2();
var a = await taskA;
var b = await taskB;

var result = Operation3(a, b);

Why is that? I would totally assume those 2 are equivalent and produce the same IL.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In the first case Operation2() doesn't run and start a task until the task returned from Operation1() completes.

In the second case both Operation1() and Operation2() run, creating and starting their tasks before you await completion of the task returned from Operation1()

over 4 years ago · Santiago Trujillo Relatório

0

In the first example you start Operation1 and wait until it is finished, then you start Operation2.

In the second example, you start Operation1 and then Operation2, after which you wait for Operation1 and then Operation2.

So Operation1 and Operation2 run in parallel in the 2nd example and sequentially in the first.

over 4 years ago · Santiago Trujillo Relatório

0

The first piece of code is equivalent to this:

var taskA = Operation1();
var a = await taskA;
// At this point the taskA is completed
var taskB = Operation2();
var b = await taskB;

Now it should be obvious why it's not equivalent with the second version:

var taskA = Operation1();
var taskB = Operation2();
// At this point both tasks are started, and probably none is completed
var a = await taskA;
var b = await taskB;

As a side note, one of these two approaches demonstrate a bad practice. Can you guess if it's the first or the second approach? You can find the answer to this quiz in the 1st revision of this answer.

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