您不应对一个对象多次调用 Dispose (CA2202)
You should not call Dispose more than one time on an object (CA2202)
我看过关于这个问题的帖子,但我似乎无法按照此处和其他在线示例来消除警告。你看到我错过了什么以避免得到 CA2202 Warning
说:
To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
我以为 using 会处理 xmlReader
。它是否也处理 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();
}
警告在 stringReader.Dispose()
行。
此代码分析警告纯属胡扯。 contract for IDisposable
要求接受对 Dispose
的额外调用并且不执行任何操作(特别是,它们不应抛出 ObjectDisposedException
或任何其他异常)。
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.
来源:IDisposable.Dispose
documentation on MSDN
不幸的是,一些框架代码是在没有阅读合约的情况下编写的,并且禁止多次调用 Dispose。那些你应该小心不要重复处理的对象。但是通用合约仍然是对于任意IDisposable
,允许多次调用Dispose
。
我看过关于这个问题的帖子,但我似乎无法按照此处和其他在线示例来消除警告。你看到我错过了什么以避免得到 CA2202 Warning
说:
To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
我以为 using 会处理 xmlReader
。它是否也处理 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();
}
警告在 stringReader.Dispose()
行。
此代码分析警告纯属胡扯。 contract for IDisposable
要求接受对 Dispose
的额外调用并且不执行任何操作(特别是,它们不应抛出 ObjectDisposedException
或任何其他异常)。
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.
来源:IDisposable.Dispose
documentation on MSDN
不幸的是,一些框架代码是在没有阅读合约的情况下编写的,并且禁止多次调用 Dispose。那些你应该小心不要重复处理的对象。但是通用合约仍然是对于任意IDisposable
,允许多次调用Dispose
。