Might be a trivial question, but it might help me in basic understanding.
Is there any important difference between two following implementations?
Task.Factory.StartNew
:
public Task<string> ReadAllTextAsync(string path) { return Task.Factory.StartNew(() => File.ReadAllText(path)); }
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(); } }
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.
NET, Task. Run is used to asynchronously execute CPU-bound code.
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.
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.
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