Called from finalizer method?


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">Q: Is there a way to tell if method
is called from within garbage collection? "urn:schemas-microsoft-com:office:office" />


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">A:


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">I assume you’re asking this because
you’ve hit some limitations in your finalizer, such as many of the state objects
in static variables in your appdomain being finalized during appdomain shutdown
or process exit.  There are two
different ways this information can be communicated:


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">1) href="http://www.gotdotnet.com/team/libraries/whitepapers/resourcemanagement/resourcemanagement.aspx">IDisposable
design pattern.  Your Dispose()
method and Finalize method may want to share an implementation for releasing the
resource, and may potentially need to do different things depending on whether
they’ve been called from the finalizer thread vs. a normal thread. style="mso-spacerun: yes">  The way we’ve solved this is with a
protected Dispose(bool disposing) method. 
The Dispose() method sets it one way, and the Finalize method sets it the
other way.


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> style="mso-spacerun: yes"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">2)
Environment.HasShutdownStarted. 
This property (which is only usable in "urn:schemas-microsoft-com:office:smarttags" /> w:st="on">Everett or later versions due to a bug in V1)
returns true if your appdomain is unloading or if the process is exiting. style="mso-spacerun: yes">  In both cases, we may be running
finalizers for object instances referred to by static variables. style="mso-spacerun: yes">  At this point, you cannot safely count
on your static state to be usable. 
(We hacked Console.WriteLine to work in this case, but that’s about
it.)


 

Comments (0)