0

Why do I see a difference in behavior when using Task.Run vs Task.Start?

Code snippet:

async Task<string> RunAsync()
{
    await Task.Delay(2);
    Console.WriteLine("In RunAsync");
    return "{}";
}

void Approach1()
{
    var task = new Task(async () => await RunAsync());

    task.Start();
    task.Wait();

    Console.WriteLine("In Approach1");
}

void Approach2()
{
     var task = Task.Run(() => RunAsync());

     task.Wait();

     Console.WriteLine("In Approach2");
}


void Main()
{
    Approach1();
    Approach2();
}

Actual output:

In Approach1
In RunAsync
In RunAsync
In Approach2

I expected the following output:

In RunAsync
In Approach1
In RunAsync
In Approach2

Note that I have come across the blog that suggests against using Task.Start: https://blogs.msdn.microsoft.com/pfxteam/2010/06/13/task-factory-startnew-vs-new-task-start/

pmohandas
  • 3,669
  • 2
  • 23
  • 25
  • 1
    There is more difference in the two examples you provide than just whether you call `Task.Run()` or `Task.Start()`. See marked duplicates for why that difference matters. Short version: in your first example, you haven't provided any mechanism to wait on the actual `RunAsync()` work, so you get to the _"In Approach1"_ output first, before `RunAsync()` gets to run. – Peter Duniho Jul 18 '17 at 05:19

1 Answers1

1

In approach1 you use await. await doesn't actually wait for anything. So you have an aysynchonous task inside your Task, which is running asynchronously. Then it fires and forgets the RunAsync method, ending the task while the async method is still running.

Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23