59

Does anyone know if there is any difference between doing Task.Factory.StartNew vs new Task followed by calling Start on the task. Looking at reflector there doesn't seem to be much difference. So perhaps the only difference is that Task.Factory.StartNewreturns a task that is already started. Is this correct?

I know that Task.Factory.StartNewand Task.Run have different default options and Task.Run is the preferred option for .Net 4.5.

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61

2 Answers2

58

I found this great article by Stephen Toub, which explains that there is actually a performance penalty when using new Task(...).Start(), as the start method needs to use synchronization to make sure the task is only scheduled once.

His advice is to prefer using Task.Factory.StartNew for .net 4.0. For .net 4.5 Task.Run is the better option.

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
  • 1
    Sometimes (rarely) you may need to use `Task` constructor, e.g: http://stackoverflow.com/q/21424084/1768303 – noseratio Feb 28 '14 at 07:47
  • 1
    More confirmation of preference to `Task.Run` by @StephenCleary [here](http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html) – StuartLC Jul 16 '15 at 11:08
  • Updated link for someone who wants to read the article - https://devblogs.microsoft.com/pfxteam/task-factory-startnew-vs-new-task-start/ – Ankur-m Feb 21 '20 at 11:17
17

Actually in the article by Stephen Toub he specifies that Task.Run() is exactly equivalent to using Task.Factory.StartNew() with the default parameters:

Task.Factory.StartNew(someAction, 
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
o_c
  • 3,965
  • 1
  • 22
  • 22
  • Not exactly equivalent when it comes to async. As Stephen Toub explains. [This has tripped me up before](http://stackoverflow.com/questions/24777253/waiting-for-async-await-inside-a-task) – Nathan Cooper Dec 15 '14 at 16:03