Q: Is there a way to tell if method is called from within garbage collection?

 

A:

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:

 

1) 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.  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.

 

 

2) Environment.HasShutdownStarted.  This property (which is only usable in Everett or later versions due to a bug in V1) returns true if your appdomain is unloading or if the process is exiting.  In both cases, we may be running finalizers for object instances referred to by static variables.  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.)