c# - 访问处置关闭

标签 c# async-await task-parallel-library

using (var memoryStream = new MemoryStream())
{
    await
        response
            .Content
            .CopyToAsync(memoryStream)
            .ContinueWith(
                copyTask =>
                {
                    using (var import = new Import())
                    {
                        var data = memoryStream.ToArray();
                        import.SaveDocumentByRecordNum(data, fileName, items[0]);
                        memoryStream.Close();
                    }
                });
}
  1. 我收到异常警告 Access to disposed object on the inner using block。
  2. memoryStream.close() 语句是必要的还是多余的?

请建议如何改进这段代码。

最佳答案

你得到的警告是因为编译器不够聪明,当你在 继续

您通常不会混合使用 async/await 和 ContinueWith,切换到仅使用 async/await 本身也会修复您的警告。以下代码将与您的旧代码一样,但不会引起警告。

using (var memoryStream = new MemoryStream())
{
    await response.Content.CopyToAsync(memoryStream).ConfigureAwait(false);

    using (var import = new Import())
    {
        var data = memoryStream.ToArray();
        trimImport.SaveDocumentByRecordNum(data, fileName, items[0]);
    }    
}

using 中对任何基于 Stream 的对象调用 Close() 也是多余的1处理它的声明也将关闭流。


1:它也是多余的,因为 MemoryStream.Close() 没有被覆盖并且 base class just calls Dispose(true)MemoryStream.Dispose(bool)除了将流标记为不可写外,不执行任何其他操作。

关于c# - 访问处置关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586595/

相关文章:

c# - 如何在 C# 中反序列化 JSON(多级)

c# - 是否可以记住 WPF 中工具栏托盘上的工具栏位置?

c# - LINQ to SQL 语句相似吗?

c# - C#读取和解析Excel文件

javascript - 如何从 Node.js 中的 Promise 和 async/await 函数返回值

javascript - 使用 AbortController 中止后如何重新启动 fetch api 请求

c# - 异步方法的返回类型必须为 void、Task 或 Task<T>

c# - 在 C# 中启动数千个任务的最佳方法是什么

c# - 取消 token 源和嵌套任务

c# - CancellationToken 阻塞线程执行