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/

1
  • 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. Commented Jul 18, 2017 at 5:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

By approach2, do you mean approach1?
thanks, edited to fix

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.