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();
}
}
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.