Why File.ReadAllLinesAsync() blocks the UI thread?

Sadly currently (.NET 5) the built-in asynchronous APIs for accessing the filesystem are not implemented consistently according to Microsoft’s own recommendations about how asynchronous methods are expected to behave.

An asynchronous method that is based on TAP can do a small amount of work synchronously, such as validating arguments and initiating the asynchronous operation, before it returns the resulting task. Synchronous work should be kept to the minimum so the asynchronous method can return quickly.

Methods like StreamReader.ReadToEndAsync do not behave this way, and instead block the current thread for a considerable amount of time before returning an incomplete Task. For example in an older experiment of mine with reading a 6MB file from my SSD, this method blocked the calling thread for 120 msec, returning a Task that was then completed after only 20 msec. My suggestion is to avoid using the asynchronous filesystem APIs from GUI applications, and use instead the synchronous APIs wrapped in Task.Run.

var lines = await Task.Run(() => File.ReadAllLines(@"D:\temp.txt"));

Update: Here are some experimental results with File.ReadAllLinesAsync:

var stopwatch = Stopwatch.StartNew();
var task = File.ReadAllLinesAsync(@"C:\6MBfile.txt");
var duration1 = stopwatch.ElapsedMilliseconds;
bool isCompleted = task.IsCompleted;
stopwatch.Restart();
var lines = await task;
var duration2 = stopwatch.ElapsedMilliseconds;
Console.WriteLine($"Create: {duration1:#,0} msec, Task.IsCompleted: {isCompleted}");
Console.WriteLine($"Await:  {duration2:#,0} msec, Lines: {lines.Length:#,0}");

Output:

Create: 450 msec, Task.IsCompleted: False
Await:  5 msec, Lines: 204,000

The method File.ReadAllLinesAsync blocked the current thread for 450 msec, and the returned task completed after 5 msec. These measurements are consistent after multiple runs.

.NET Core 3.1.3, C# 8, Console App, Release build (no debugger attached), Windows 10, SSD Toshiba OCZ Arc 100 240GB


.NET 6 update. The same test on the same hardware using .NET 6:

Create: 19 msec, Task.IsCompleted: False
Await:  366 msec, Lines: 204,000

The implementation of the asynchronous filesystem APIs has been improved on .NET 6, but still they are far behind the synchronous APIs (they are about
2 times slower, and not totally asynchronous). So my suggestion to
use the synchronous APIs wrapped in Task.Run still holds.

Leave a Comment