访问处置关闭

Access to disposed closure

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() 语句是必要的还是多余的?

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

你得到的警告是因为编译器不够聪明,当你在 ContinueWith 中使用 MemoryStream 时,无法知道你永远不会在内存流的 using 块之外.

您通常不会混合使用 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]);
    }    
}

在任何基于 Stream 的对象上调用 Close() 也是多余的 1 当它在 using 语句中时,因为处理它会也关闭流。


1:它也是多余的,因为 MemoryStream.Close() 没有被覆盖,并且 base class just calls Dispose(true) and MemoryStream.Dispose(bool) 除了将流标记为不可写之外没有做任何事情。