Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!