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?
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.
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