Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew vs Async methods

Tags:

Might be a trivial question, but it might help me in basic understanding.

Is there any important difference between two following implementations?

  1. Task.Factory.StartNew:

    public Task<string> ReadAllTextAsync(string path) {     return Task.Factory.StartNew(() => File.ReadAllText(path)); } 
  2. Async method on StreamReader:

    public async Task<string> ReadAllTextAsync(string path) {     using (var stream = File.OpenRead(path))     using (var reader = new StreamReader(stream)) {         return await reader.ReadToEndAsync();     } } 
like image 919
Andrey Shchekin Avatar asked Feb 04 '13 07:02

Andrey Shchekin


People also ask

What is the difference between task run () and TaskFactory StartNew () methods?

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 is task factory StartNew?

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.

Is Task run async?

NET, Task. Run is used to asynchronously execute CPU-bound code.

What does Task factory do 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.


1 Answers

Yes, there's a crucial difference: the Task.Factory.StartNew is not preserving the synchronization context whereas when using async/await this context is preserved. For example in an ASP.NET application this means that if you use Task.Factory.StartNew the HttpContext might not be accessible inside the task whereas if you use async/await it will be available.

There's also another important difference with the example you provided. In the first case you are using a blocking API: File.ReadAllText(path) whereas in the second case you are using an I/O Completion port with a true asynchronous I/O operation. This means that in the first case you are jeopardizing the thread on which this task executes during the entire time this task is executing whereas in the second case this thread is free thanks to an I/O Completion Port.

like image 125
Darin Dimitrov Avatar answered Oct 22 '22 13:10

Darin Dimitrov