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.StartNew
returns a task that is already started. Is this correct?
I know that Task.Factory.StartNew
and Task.Run
have different default options and Task.Run
is the preferred option for .Net 4.5.
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!
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With