I am currently getting the CA2202 (Do not dispose objects multiple times) on code that I am analysing. The warning refers to HttpApplication.Dispose
method that I am overriding. I know the IDispose.Dipose
method should not be virtual or be overriden but this a result of Microsoft implementing the IDispose.Dispose
as virtual in the HttpApplication
class and not providing a virtual protected Dispose method.
The warning appears to be complaining about the calling of the base.Dispose
method. I am calling the base Dispose method in case the base class needs to close or dispose of any objects. And also suspect that I'll probably end up with the CA2215 (Dispose methods should call base class dispose) warning otherwise.
Does anyone know why I am getting this (CA2202) warning and what to do about it?
I am tempted to suppress it but the MSDN docs says that it should never be suppressed.
The sub class looks like the following (it has been shortened for brevity and you can assume that the _container
field has been initialised):
public class MyHttpApplication : HttpApplication
{
private bool _disposed;
private IDisposable _container;
public sealed override void Dispose()
{
if (_disposed)
return;
try
{
Dispose(true);
GC.SuppressFinalize(this);
}
finally
{
//The following lines is what causes the CA2202 code analysis warning
base.Dispose();
}
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
try
{
if (disposing && _container != null)
{
_container.Dispose();
}
}
finally
{
_disposed = true;
}
}
}
It seems there's no way out without suppressing something. My solution was to put the call to base.Dispose() inside the Dispose(bool) method then suppress CA2215, for which the MSDN docs say "It is safe to suppress a warning from this rule if the call to base.Dispose occurs at a deeper calling level than the rule checks."