【问题标题】:Proper way to use DisposeAsync on C# streams在 C# 流上使用 DisposeAsync 的正确方法
【发布时间】:2019-11-04 15:26:18
【问题描述】:

我正在编写一个将单独的文本行异步写入文件的方法。如果它被取消,它会删除创建的文件并跳出循环。

这是工作正常的简化代码...我标记了 2 个点,我不确定它们是如何处理的。我希望代码在任何情况下都不会阻塞线程。

public async Task<IErrorResult> WriteToFileAsync(string filePath,
                                                 CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();

    using var stream = new FileStream(filePath, FileMode.Create);
    using var writer = new StreamWriter(stream, Encoding.UTF8);

    foreach (var line in Lines)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            //
            // [1] close, delete and throw if cancelled
            //
            writer.Close();
            stream.Close();
            if (File.Exists(filePath))
                File.Delete(filePath);
            throw new OperationCanceledException();
        }

        // write to the stream
        await writer.WriteLineAsync(line.ToString());
    }

    //
    // [2] flush and let them dispose
    //
    await writer.FlushAsync();
    await stream.FlushAsync();
    // await stream.DisposeAsync(); ??????
    return null;
}

1

我在FileStream 和StreamWriter 上调用Close(),我认为它会同步运行并阻塞线程。我该如何改进呢?我不想等待它将缓冲区刷新到文件中然后删除文件。

2

我想Dispose 方法将被调用,而不是using 范围末尾的DisposeAsync。 (这个假设正确吗?)。

所以Dispose 阻塞了线程,为了防止我先用FlushAsync 刷新,以便Dispose 执行less 的事情。 (这在多大程度上是真的?)

我也可以删除using,而是在这两个地方手动写入DisposeAsync。但这会降低可读性。

如果我用useAsync = true 打开FileStream,它会在using 块结束时自动调用DisposeAsync 吗?


任何解释或上述代码执行得更好的变体表示赞赏。

【问题讨论】:

  • 如果Stream 类正在实现IAsyncDisposable,您可以确保DisposeAsync 最终会被await using 流调用。但是它没有实现这个接口……
  • @TheodorZoulias 感谢您提供有用的信息。我不知道我能做到await using :)
  • 是的,它是新的 C# 8 语法。 :-)
  • 噢!我提到Stream 类没有基于documentation 实现IAsyncDisposable。我应该看看Object Explorer。不幸的是,在线文档还没有更新 C# 8 的新特性。
  • @TheodorZoulias 是的 Stream 实现了 IAsyncDisposable 和 await using 非常有效。也许文档已经过时了

标签: c# asynchronous stream


【解决方案1】:

如你所见,using 语句将调用Dispose(),而不是DisposeAsync()。

C# 8 带来了新的await using 语法,但由于某种原因,What's new in C# 8.0 文章中没有提到它。

但它是mentioned elsewhere。

await using var stream = new FileStream(filePath, FileMode.Create);
await using var writer = new StreamWriter(stream, Encoding.UTF8);

但也请注意,这仅在以下情况下有效:

  • 您使用的是 .NET Core 3.0+,因为那是引入 IAsyncDisposable 的时候,或者
  • 安装Microsoft.Bcl.AsyncInterfaces NuGet 包。虽然这只是添加了接口,并不包括使用它的Stream 类型(FileStream、StreamWriter 等)的版本。

即使在Announcing .NET Core 3.0 的文章中,IAsyncDisposable 也只是顺带提及,从未展开。

另一方面,你不需要这样做(我现在明白为什么了):

writer.Close();
stream.Close();

自the documentation for Close says:

此方法调用 Dispose,指定true 释放所有资源。您不必专门调用 Close 方法。相反,请确保正确处置每个 Stream 对象。

由于您使用的是using,Dispose()(或DisposeAsync())将被自动调用,Close 不会做任何尚未发生的事情。

因此,如果您确实需要专门关闭文件,但想要异步执行,只需调用 DisposeAsync() 即可。它做同样的事情。

await writer.DisposeAsync();

public async Task<IErrorResult> WriteToFileAsync(string filePath,
                                                 CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();

    await using var stream = new FileStream(filePath, FileMode.Create);
    await using var writer = new StreamWriter(stream, Encoding.UTF8);

    foreach (var line in Lines)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            // not possible to discard, FlushAsync is covered in DisposeAsync
            await writer.DisposeAsync(); // use DisposeAsync instead of Close to not block

            if (File.Exists(filePath))
                File.Delete(filePath);
            throw new OperationCanceledException();
        }

        // write to the stream
        await writer.WriteLineAsync(line.ToString());
    }

    // FlushAsync is covered in DisposeAsync
    return null;
}

【讨论】:

  • 感谢您的信息。我Close 流,因为我想立即删除文件,Dispose 发生得太晚了,给了我it is being used by another process 异常
  • 啊,好的。这完全有道理。
  • 这不是 .NET Core 3.0+ - Microsoft.Bcl.AsyncInterfaces 中提供了必要的 API; 问题是Stream等还没有实现这个接口(在.NET Core 3.0之前);但在一般意义上:feature 可以工作 if 组件获取 ref 并实现 API
  • @Bizhan 我看不到一种方法可以丢弃迄今为止写入缓冲区的内容而不写入它。我查看了the source code,在FileStream 或StreamWriter 中都看不到任何可以让你这样做的东西。
  • 对了,DisposeAsync() will flush the buffer,所以你不需要单独打电话给FlushAsync()。
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
相关资源
最近更新 更多