Openread asynchronously

I use the following C # code to read a tiny text file through a network share:

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

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

 File.OpenRead(filePath) 

This is probably due to the fact that Windows should allow file sharing and get file locks over the network. Since this method call is not asynchronous, it blocks my current thread for several seconds.

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

+5
source share
1 answer

No, unfortunately, this is not enough in the Win32 API. Device drivers have the concept of asynchronous open, so the infrastructure exists; but the Win32 API does not disclose this functionality.

Naturally, this means that .NET also cannot reveal this functionality. However, you can use a "fake asynchronous" operation, that is, wrap your file read in Task.Run so that your UI thread is not blocked. However, if you are using ASP.NET, do not use Task.Run ; just keep the (blocking) file open as it is.

+8
source

Source: https://habr.com/ru/post/1216655/


All Articles