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.
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 itsDispose
method is called multiple times. Instance methods other thanDispose
can throw anObjectDisposedException
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.