加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 异步/等待并打开FileStream?

发布时间:2020-12-15 07:49:43 所属栏目:百科 来源:网络整理
导读:尝试确定是否正在正确使用ReadAsync和CopyToAsync等Stream方法时遇到以下问题: C# 4.5 file read performance sync vs async 在这个问题中,我在接受的答复中看到以下内容: Most notably,your “async” test does not use async I/O; with file streams, y
尝试确定是否正在正确使用ReadAsync和CopyToAsync等Stream方法时遇到以下问题:
C# 4.5 file read performance sync vs async

在这个问题中,我在接受的答复中看到以下内容:

Most notably,your “async” test does not use async I/O; with file
streams,you have to explicitly open them as asynchronous or else
you’re just doing synchronous operations on a background thread.

在他的异步IO代码中,他正在使用以下内容来异步打开FileStream:

var file = new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read,4096,true)

所以我想知道如果你打算使用诸如CopyToAsync之类的方法,无论你是否打开如上所示的底层FileStream,而不是像下面这样做一些简单的事情:

File.Open(filename,FileMode.Open)

CopyToAsync的实际文档中的示例如何演示打开底层FileStream:
https://msdn.microsoft.com/en-us/library/hh159084(v=vs.110).aspx

如果打开底层FileStream的方式无关紧要,FileStream构造函数的useAsync参数是做什么的?

解决方法

So I was wondering if you intend to use methods such as CopyToAsync whether you should open the underlying FileStream as shown above?

是.原因大多是历史的.

首先,在Windows上,HANDLEs (including file handles) must be opened/created explicitly with an asynchronous flag if you want to do asynchronous (OVERLAPPED) operations on them.

但是,the old Windows 95/98/ME line only supported asynchronous operations on serial port and IOCTL (device driver) handles.该平台线路不支持磁盘文件上的异步I / O.而the original .NET did support 98/ME,所以原来的FileStream只是使用同步I / O.我认为(但不是绝对肯定)Win98 / ME上的APM methods(如FileStream.BeginRead)可能只是使用所谓的“asynchronous delegates”(在线程池线程上执行FileStream.Read的同步方法)来实现.

所以,这是为什么文件流处理默认情况下不使用异步标志打开的历史原因.

Which is how the example in the actual documentation for CopyToAsync demonstrates

不幸的是,很多MSDN的例子都是质量差的.如果您从“以下是一个如何调用此特定方法的示例”的角度来接近他们,则可以使用它们,但从“以下是使用此方法的生产质量代码的示例”的角度来看,并不那么好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读