gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:43:45 24 4
gpt4 key购买 nike

在尝试确定我是否正确使用 Stream 方法(例如 ReadAsyncCopyToAsync)时,我遇到了以下问题: 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。我认为(但不是绝对确定)APM methods (如 FileStream.BeginRead)在 Win98/ME 上可能只是使用所谓的 "asynchronous delegates" 实现的(它只是在线程池线程上执行类似 FileStream.Read 的同步方法)。

因此,这就是默认情况下使用异步标志打开文件流句柄的历史原因。

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

不幸的是,许多 MSDN 示例质量很差。如果您从“这是一个如何调用此特定方法的示例”的角度来处理它们,它们是可以的,但如果从“这是一个使用此方法的生产质量代码的示例”的角度来看,它们就不是那么好。

关于c# - 异步/等待并打开 FileStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37041844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com