Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew vs new Task

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.

like image 971
NeddySpaghetti Avatar asked Feb 28 '14 05:02

NeddySpaghetti


People also ask

What is the difference between task run and task factory StartNew?

Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!

What does task factory StartNew do?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

What is the use of task factory in C#?

The TaskFactory class, which creates Task and Task<TResult> objects. You can call the overloads of this method to create and execute a task that requires non-default arguments.

Does task run create new thread?

Starting a new task queues that task for execution on a threadpool thread. Threads execute in the context of the process (eg. the executable that runs your application). If this is a web application running under IIS, then that thread is created in the context of the IIS worker process.


2 Answers

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.

like image 58
NeddySpaghetti Avatar answered Sep 27 '22 22:09

NeddySpaghetti


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); 
like image 44
o_c Avatar answered Sep 27 '22 22:09

o_c