RE: Code Analysis - CA1816 (CallGCSuppressFinalize)
- From: Misbah Arefin <MisbahArefin@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 4 Apr 2008 19:19:01 -0700
A disposable type needs to implement IDisposable & provide a public
Dispose(void) method that ends the object’s lifetime. If the type is not
sealed, it should provide a protected Dispose(bool disposing) method where
the actual cleanup logic lives. Dispose(void) then calls Dispose(true)
followed by GC.SuppressFinalize(this). If your object needs a finalizer,
then the finalizer calls Dispose(false). The cleanup logic in Dispose(bool)
needs to be written to run correctly when called explicitly from
Dispose(void), as well as from a finalizer thread. Dispose(void) and
Dispose(bool) should be safely runnable multiple times, with no ill effects
//the dispose pattern
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//release objects
if (_Connection != null)
{
_Connection.Dispose();
_Connection = null;
}
}
}
--
Misbah Arefin
https://mcp.support.microsoft.com/profile/MISBAH.AREFIN
http://www.linkedin.com/in/misbaharefin
"NvrBst" wrote:
Code Analysis always returns the following message on a bunch of my.
classes.
Warning 75 CA1816 : Microsoft.Usage : Change 'xxx.Dispose()' to call
'GC.SuppressFinalize(object)'. This will prevent unnecessary
finalization of the object once it has been disposed and it has fallen
out of scope.
None of my classes have a finalizer, they all simply have the
following (or very simular to the following)
----------
private bool disposed = false;
public void Dispose() { Dispose(true); }
protected virtual void Dispose(bool disposing) {
if(!disposed) {
if(disposing && slimLock != null) slimLock.Dispose();
disposed = true;
}
}
----------
Joe Duffy's Weblog (http://www.bluebytesoftware.com/blog/2005/04/08/
DGUpdateDisposeFinalizationAndResourceManagement.aspx)
--Says not to call Dispose if my class doesn't have the "~MyClass()"
finalizer method.
MSDN (http://msdn2.microsoft.com/en-us/library/ms182269.aspx)
--Says, basically, don't ignore this warning and to add the code.
Should I be calling the SupressFinalize anyway (IE doesn't hurt
anything performance wise), or just ignore the Code Analysis warning?
Or 'something strange with my code because I dont get the warning'
kind of thing?
Thanks :) NB
- References:
- Code Analysis - CA1816 (CallGCSuppressFinalize)
- From: NvrBst
- Code Analysis - CA1816 (CallGCSuppressFinalize)
- Prev by Date: RE: try-catch question
- Next by Date: Re: try-catch question
- Previous by thread: Code Analysis - CA1816 (CallGCSuppressFinalize)
- Next by thread: Re: Code Analysis - CA1816 (CallGCSuppressFinalize)
- Index(es):
Relevant Pages
|