异步OpenRead [英] OpenRead asynchronously

查看:76
本文介绍了异步OpenRead的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下C#代码通过网络共享读取微小的文本文件:

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();
}

即使文本文件很小(小于10 KB),该操作有时也需要花费约7秒钟才能运行.发生这种情况时,我注意到大部分时间都花在了

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)

这可能是由于Windows必须解析文件共享并通过网络获取文件上的锁的缘故.由于该方法调用不是异步的,因此这将阻塞我当前的线程几秒钟.

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.

有没有一种安全的方法可以从磁盘异步读取文件,该文件也可以异步执行OpenRead?

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

推荐答案

不,不幸的是,Win32 API中缺少此功能.设备驱动程序确实具有异步打开"的概念,因此基础结构就在那里.但是Win32 API没有公开此功能.

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.

自然,这意味着.NET也无法公开该功能.但是,您可以使用伪异步"操作-即,将文件包装在Task.Run中,以免UI线程被阻塞.但是,如果您使用的是ASP.NET,则不要使用Task.Run.只需保持(阻止)文件为打开状态即可.

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.

这篇关于异步OpenRead的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆