如何摆脱 "Object 'object' can be disposed more than once in method"

How to get rid of "Object 'object' can be disposed more than once in method"

我正在使用 Visual Studio 工具分析代码,我收到此消息:

Object 'FileStream' can be disposed more than once in method 'BitmapFormat.WriteBitmap(byte[], int, int)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

我尝试在对象上显式调用 disposed 但无济于事。

这是方法:

Stream FileStream = null;
try
{
    FileStream = File.Open("finger.bmp", FileMode.Create, FileAccess.Write);
    BinaryWriter TmpBinaryWriter = new BinaryWriter(FileStream);
    TmpBinaryWriter.Write(StructToBytes(BmpHeader, 14));
    TmpBinaryWriter.Write(StructToBytes(BmpInfoHeader, Marshal.SizeOf(BmpInfoHeader)));

    //µ÷ÊÔ°åÐÅÏ¢
    for (ColorIndex = 0; ColorIndex < m_nColorTableEntries; ColorIndex++)
    {
        ColorMask[ColorIndex].redmask = (byte)ColorIndex;
        ColorMask[ColorIndex].greenmask = (byte)ColorIndex;
        ColorMask[ColorIndex].bluemask = (byte)ColorIndex;
        ColorMask[ColorIndex].rgbReserved = 0;

        TmpBinaryWriter.Write(StructToBytes(ColorMask[ColorIndex], Marshal.SizeOf(ColorMask[ColorIndex])));
    }

    //ͼƬÐýת£¬½â¾öÖ¸ÎÆͼƬµ¹Á¢µÄÎÊÌâ
    RotatePic(buffer, nWidth, nHeight, ref ResBuf);

    //дͼƬ
    //TmpBinaryWriter.Write(ResBuf);
    byte[] filter = null;
    if (w - nWidth > 0)
    {
        filter = new byte[w - nWidth];
    }
    for (int i = 0; i < nHeight; i++)
    {
        TmpBinaryWriter.Write(ResBuf, i * nWidth, nWidth);
        if (w - nWidth > 0)
        {
            TmpBinaryWriter.Write(ResBuf, 0, w - nWidth);
        }
    }

    TmpBinaryWriter.Close();
    FileStream.Close(); // <----- THE WARNING IS HERE
}
finally
{
    if (FileStream != null)
        FileStream.Dispose();
}

如果我删除 try finally 块,也会发生同样的情况。即使我使用 using 语句。

如何避免?

试着摆脱这条线。您在 finally 块中调用 dispose,它总是 运行。所以你可以删除这一行。

FileStream的具体情况下,不需要dispose关闭文件,只需要使用Close方法即可。

这可能会发生,因为您可能会尝试执行

FileStream.Close(),

FileStream.Dispose()

在你的情况下使用 Dispose 没有意义,你可以只使用 Close 方法。 close 方法将执行具有 'true' 值的 Dispose 方法。

请观看 'FileStream.Close()' 方法的解释:

https://msdn.microsoft.com/en-us/library/aa328800(v=vs.71).aspx

This implementation of Close calls the Dispose method passing a true value.