Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 997
user42 Avatar asked Jun 08 '13 16:06

user42


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 await start a task?

No, async await is just made to allow code to run whilst something else is blocking, and it doesn't do Task.


1 Answers

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.

like image 95
Stephen Cleary Avatar answered Sep 25 '22 04:09

Stephen Cleary