-1

I've seen posts on this question but I can't seem to get rid of the warning by following the examples here and other places online. Do you see what I am missing to avoid getting the CA2202 Warning that says:

To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

I thought the using would dispose the xmlReader. Is it also disposing the stringReader ?

StringReader stringReader = null;
try
{
    stringReader = new StringReader(mOutputXmlString);
    using (XmlReader xmlReader = XmlReader.Create(stringReader, lXmlReaderSettings))
    {
        addResponse = (AddResponseStructure)mDeserializer.Deserialize(xmlReader);
        alertDetail = new AlertHostDetail(addResponse);
    }
}
catch
{
    _loggingManager.Log(LoggingHelpers.LoggingLevel.Error, "Error deserializing object.");
}
finally
{
    if (stringReader != null)
        stringReader.Dispose();
}

The warning is on the stringReader.Dispose() line.

Igor
  • 60,821
  • 10
  • 100
  • 175
Rich
  • 6,470
  • 15
  • 32
  • 53
  • 1
    When you exit the using statement the reader is automatically disposed. – jdweng Aug 25 '20 at 17:16
  • Please have a look on https://stackoverflow.com/a/75483/2641352 – miguelmpn Aug 25 '20 at 17:20
  • 1
    To comment on the comment by @jdweng - both `xmlReader` and `stringReader` will be disposed of upon exiting the `using` statement block either normally or via a thrown exception. – phuzi Aug 25 '20 at 17:22
  • 3
    @Rich Where `IDisposable`s are consumed by an `IDisposable` it's common in .Net that the consumed `IDisposable` is also disposed when the consumer is. – phuzi Aug 25 '20 at 17:27
  • 1
    @phuzi To be clear, the double dispose is only because the `XmlReader` disposes the `StringReader`. The code shown here does not double dispose. – StackOverthrow Aug 25 '20 at 18:28

1 Answers1

2

This code analysis warning is total baloney. The contract for IDisposable requires that extra calls to Dispose are accepted and do nothing (in particular, they should not throw ObjectDisposedException or any other exception).

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. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

Source: IDisposable.Dispose documentation on MSDN

Unfortunately some framework code was written without reading the contract, and forbids calling Dispose more than once. Those objects you should be careful not to double dispose. But the universal contract is still that for an arbitrary IDisposable, calling Dispose multiple times is permitted.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720