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();
}
});
}
- 我收到异常警告 Access to disposed object on the inner using block。
- 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/