user42
user42

Reputation: 347

await Task.Factory.StartNew(() => versus Task.Start; await Task;

Is there any functional difference between these two forms of using await?

  1. string x = await Task.Factory.StartNew(() => GetAnimal("feline"));
    
  2. Task<string> myTask = new Task<string>(() => GetAnimal("feline"));
    myTask.Start();
    string z = await myTask;
    

Specifically, in what order is each operation called in 1.? Is StartNew called and then is await called, or is await called first in 1.?

Upvotes: 27

Views: 28986

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456407

When you're writing code with async and await, you should use Task.Run whenever possible.

The Task constructor (and Task.Start) are holdovers from the Task Parallel Library, used to create tasks that have not yet been started. The Task constructor and Task.Start should not be used in async code.

Similarly, TaskFactory.StartNew is an older method that does not use the best defaults for async tasks and does not understand async lambdas. It can be useful in a few situations, but the vast majority of the time Task.Run is better for async code.

Upvotes: 33

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

StartNew is just a short hand for creating and starting a task. If you want to do something to the Task instance before you start it, use the constructor. If you just want to create and start the task immediately, use the short hand.

Documentation for StartNew says:

Calling StartNew is functionally equivalent to creating a task by using one of its constructors, and then calling the Task.Start method to schedule the task for execution.

Upvotes: 18

Related Questions