Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenRead asynchronously

I'm using the following C# code to read a tiny text file over a network share:

string fileContent;
using (var stream = File.OpenRead(filePath))
using (var reader = new StreamReader(stream, FileEncoding))
{
    fileContent = await reader.ReadToEndAsync();
}

Even though the text file is very small (less than 10 KB) this operation sometimes takes ~7 seconds to run. When that happens, I've noticed most of the time is spent on

File.OpenRead(filePath)

This is probably due to Windows having to resolve the file share and to acquire locks on the file over the network. As that method call is not asynchronous, this is blocking my current thread for several seconds.

Is there a safe way to read a file from disk asynchronously that also performs OpenRead asynchronously?

like image 933
roim Avatar asked Apr 02 '15 01:04

roim


1 Answers

No, unfortunately this is missing in the Win32 API. Device drivers do have the notion of an "asynchronous open", so the infrastructure is there; but the Win32 API does not expose this functionality.

Naturally, this means that .NET can't expose that functionality, either. You can, however, use a "fake asynchronous" operation - i.e., wrap your file read within a Task.Run, so that your UI thread isn't blocked. However, if you're on ASP.NET, then don't use Task.Run; just keep the (blocking) file open as it is.

like image 183
Stephen Cleary Avatar answered Oct 30 '22 15:10

Stephen Cleary