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 toDispose
are accepted and do nothing (in particular, they should not throwObjectDisposedException
or any other exception).Source:
IDisposable.Dispose
documentation on MSDNUnfortunately 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
, callingDispose
multiple times is permitted.