Is there any functional difference between these two forms of using await?
string x = await Task.Factory.StartNew(() => GetAnimal("feline"));
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.?
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.
No, async await is just made to allow code to run whilst something else is blocking, and it doesn't do Task.
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.
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