Search code examples
c#asynchronoustask

What is the different between calling Task.Run() vs. DoSomethingAsync()?


What is the difference between these two:

Task.Run(() => File.ReadAllText(path));

File.ReadAllTextAsync(path);

I would expect the second one to be faster, sure, but generally is there any security reason I should not use the first method? I'm using File.ReadAllText as an example but the focus of this question for me is the asynchronous part.


Solution

  • Based on my understanding of the two I would categorize like this

    1. File.ReadAllTextAsync(path); performs a non blocking async operation that immediately return a Task which can be awaited

    2. Task.Run(() => File.ReadAllText(path)); performs a synchronous blocking operation but offloads it to a new thread from the thread pool

    Given these differences its obvious why File.ReadAllTextAsync(path); is better in case where many i/o operations happen as the Task.Run(() => File.ReadAllText(path)); will hold a thread until the operation is completed.

    Summary

    both methods will perform non-blocking operations on the main thread the difference is that Task.Run(() => File.ReadAllText(path)); will tie up a thread for the duration of the operation.