通过


ZipArchive.CreateAsync 急切地加载 ZIP 存档条目

ZipArchive.CreateAsync 现在,在方法调用期间急切地加载所有 ZIP 存档条目。 此更改可确保访问 ZipArchive.Entries 属性不会对基础流执行同步读取,这与异步编程模式保持一致。

已引入的版本

.NET 11 预览版 1

以前的行为

以前,使用CreateAsync创建ZipArchive时,访问Entries属性可能会导致对基础流执行同步(阻塞)读取操作。 此行为与方法的 CreateAsync 异步性质不一致,可能会导致不支持同步读取的流出现问题。

using System.IO;
using System.IO.Compression;

using var stream = new FileStream("archive.zip", FileMode.Open);
using var archive = await ZipArchive.CreateAsync(stream, ZipArchiveMode.Read);

// This call performs synchronous reads on the stream.
// Might throw if the file entries are malformed
// or if the stream doesn't support synchronous reads.
var entries = archive.Entries;

新行为

从 .NET 11 开始,ZIP 存档的中心目录在调用 ZipArchive.CreateAsync 方法时异步读取。 CreateAsync 现在会在调用期间引发与格式不正确的条目或读取中央目录相关的任何异常。 后续访问Entries属性时,不会对基础流执行任何读取操作。

using System.IO;
using System.IO.Compression;

using var stream = new FileStream("archive.zip", FileMode.Open);

// This call eagerly loads the ZIP archive entries.
// Any exceptions related to malformed entries are surfaced here.
using var archive = await ZipArchive.CreateAsync(stream, ZipArchiveMode.Read);

// Accessing Entries no longer performs stream read operations.
var entries = archive.Entries;

破坏性变更的类型

此更改为行为更改

更改原因

此更改是在处理异步流时改进一致性和可靠性。 通过在调用期间急切地加载条目,API 稍后将避免意外的同步读取操作。 避免同步读取对于最终可能会阻塞的流尤其重要,直到数据可用(例如网络流)。 这与批准的 API 设计保持一致,并提供更可预测的编程体验。

有关详细信息,请参阅 dotnet/runtime#121938dotnet/runtime#121624API 设计讨论

如果代码使用 ZipArchive.CreateAsync,请确保处理 InvalidDataException 方法调用中的 CreateAsync 异常。 此异常可能已在以前的 .NET 版本中引发(例如,找不到 ZIP 中央目录时),但现在也会针对以前仅在访问 Entries 该属性时发现的格式不正确的条目引发此异常。

受影响的 API