gpt4 book ai didi

c# - "Object can be disposed of more than once"错误

转载 作者:IT王子 更新时间:2023-10-29 03:59:02 26 4
gpt4 key购买 nike

当我对以下代码块运行代码分析时,我收到此消息:

对象“stream”可以在方法“upload.Page_Load(object, EventArgs)”中处理多次。为避免生成 System.ObjectDisposedException,您不应对一个对象多次调用 Dispose。

using(var stream = File.Open(newFilename, FileMode.CreateNew))
using(var reader = new BinaryReader(file.InputStream))
using(var writer = new BinaryWriter(stream))
{
var chunk = new byte[ChunkSize];
Int32 count;
while((count = reader.Read(chunk, 0, ChunkSize)) > 0)
{
writer.Write(chunk, 0, count);
}
}

我不明白为什么它会被调用两次,以及如何修复它以消除错误。有帮助吗?

最佳答案

我努力解决这个问题并找到了示例 here非常有帮助。我将发布代码以供快速查看:

using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// Use the writer object...
}
}

用 try/finally 替换外部 using 语句,确保在 StreamWriter 中使用流后将流清空,并在处理前检查以确保它在 finally 中不为空。

Stream stream = null;
try
{
stream = new FileStream("file.txt", FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(stream))
{
stream = null;
// Use the writer object...
}
}
finally
{
if(stream != null)
stream.Dispose();
}

这样做消除了我的错误。

关于c# - "Object can be disposed of more than once"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3982719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com