Can't seem to see why FXCop is complaining that I am disposing the memoryStream object more than once. As near as I can tell, I'm only disposing of it in the finally block.

Full error message is:

CA2202 Do not dispose objects multiple times Object 'memoryStream' can be disposed more than once in method 'MessageTransform.GetEnvelope(Message)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 48 Api MessageTransform.cs 48

        var memoryStream = new MemoryStream();
        try
        {
            var messageBuffer = message.CreateBufferedCopy(int.MaxValue);
            var xPathNavigator = messageBuffer.CreateNavigator();

            var xmlWriter = XmlWriter.Create(memoryStream);
            xPathNavigator.WriteSubtree(xmlWriter);
            xmlWriter.Flush();
            xmlWriter.Close();

            memoryStream.Position = 0;
            var xdoc = XDocument.Load(XmlReader.Create(memoryStream));
            return xdoc;
        }
        catch (ApplicationException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
        finally
        {
            memoryStream.Dispose();
        }

If I wrap the same code in a using block I get the same error.

using (var memoryStream = new MemoryStream())
{
    var messageBuffer = message.CreateBufferedCopy(int.MaxValue);
    var xPathNavigator = messageBuffer.CreateNavigator();

    var xmlWriter = XmlWriter.Create(memoryStream);
    xPathNavigator.WriteSubtree(xmlWriter);
    xmlWriter.Flush();
    xmlWriter.Close();

    memoryStream.Position = 0;
    var xdoc = XDocument.Load(XmlReader.Create(memoryStream));
    return xdoc;
}

Is this just an issue with a hyperactive FXCop or does using a using block or .Dispose() somehow not apply to a System.IO.MemoryStream?

有帮助吗?

解决方案

The XmlWriter can dispose the stream from its Close method, which is what the rule is picking up. However, this behavior is conditional and should not be invoked in an XmlWriter created for a stream in the way you describe.

其他提示

As Nicole described, the XmlWriters' Close can dispose the Memorystream-object, which is causing the error to be raised.

I do want to point out that a using statement and try-finallystatement are the exact same thing. The compiler translates using statements into a tryblock with your execution and a Dispose() in the finallyblock.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top