“物体可以被处置一次以上”。错误 [英] "Object can be disposed of more than once" error

查看:60
本文介绍了“物体可以被处置一次以上”。错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run code analysis on the following chunk of code I get this message:

对象'stream'可以在方法'upload.Page_Load中被处置多次。 (对象,EventArgs)。为了避免生成System.ObjectDisposedException,您不应在对象上调用Dispose多次。

Object 'stream' can be disposed more than once in method 'upload.Page_Load(object, EventArgs)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

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);
    }
}

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

I don't understand why it might be called twice, and how to fix it to eliminate the error. Any help?

推荐答案

我为此问题苦苦挣扎,找到了示例此处非常有帮助。我将发布代码以便快速查看:

I struggled with this problem and found the example here to be very helpful. I'll post the code for a quick view:

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

使用try / finally替换外部using语句,并确保使用后都将流都为空

Replace the outer using statement with a try/finally making sure to BOTH null the stream after using it in StreamWriter AND check to make sure it is not null in the finally before disposing.

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();
}

这样做可以清除我的错误。

Doing this cleared up my errors.

这篇关于“物体可以被处置一次以上”。错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆