Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing of object multiple times

Tags:

c#

ca2202

I have the following code, which uses a stream to open and modify an Open XML document, and then save the new binary representation of that stream:

MemoryStream stream = null;
try
{
    stream = new MemoryStream();
    stream.Write(this.GetBinaryRepresentation(), 0, this.GetBinaryRepresentation().Length);

    using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true))
    {
        OfficeDocument.ModifyDocument(document);
        this.SetBinaryRepresentation(stream.ToArray());
        stream = null;
    }
}
finally
{
    if (stream != null)
    {
        stream.Dispose();
    }
}

I had originally used two using blocks (one for the MemoryStream and the second for the WordprocessingDocument), but received warning CA2202: "Object 'stream' can be disposed more than once in method..." Per the MSDN article, I modified the code to above (converting the outer using to a try), but I am still receiving this warning.

I'm unsure of how I can structure this method to ensure that Dispose is called exactly once on the stream. I would prefer not to simply suppress this warning since the MSDN article states that you shouldn't rely on Dispose being safely callable multiple times.

like image 279
Andrew Keller Avatar asked Dec 09 '22 23:12

Andrew Keller


1 Answers

Disposing of an object multiple times should always be safe. From the documentation for Dispose:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times.

That being said, a using statement is definitely the way to go here. The only reason you'd receive that method was if you were explicitly disposing of the object, which would not be required, as the using statement should always dispose the object exactly once.

like image 85
Reed Copsey Avatar answered Dec 11 '22 11:12

Reed Copsey