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/