Task.Run
Prefer Task.Run
over Task.Factory.StartNew
over new Task()
.
Task.Factory.StartNew
Task.Factory.StartNew
is considered dangerous and should only be used in very specific circumstances.TaskCreationOptions.LongRunning
. In the current implementation of .NET this creates a new thread for your task, instead of running it on the threadpool. This could change between implementations / platforms, so should not be relied upon. Only do this if you have profiled your application and found it to be necessary. If you really need a new thread, consider Thread.Start
.Task.Factory.StartNew(MyMethod, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
Task.Run(() => MyMethod()); // equivalent to the above
new Task()
.Start()
it manually if you need to separate the task’s creation from its execution, such as when you conditionally execute tasks that you’ve created.var task = new Task(MyMethod, CancellationToken.None, TaskCreationOptions.DenyChildAttach);
task.Start(TaskScheduler.Default);
Task.Run(() => MyMethod()); // equivalent to the above