Ok, it\'s known that GC implicitly calls Finalize
methods on objects when it identifies that object as garbage. But what happens if I do a GC.Collect()
When the garbage is collected (whether in response to memory pressure or GC.Collect()
), the objects requiring finalization are put to finalization queue.
Unless you call GC.WaitForPendingFinalizers()
, the finalizers may continue to execute in the background long after garbage collection has finished.
BTW, there is no guarantee finalizers will be called at all. From MSDN...
The Finalize method might not run to completion or might not run at all in the following exceptional circumstances:
- Another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain and so on). Because the runtime attempts to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely.
- The process terminates without giving the runtime a chance to clean up. In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification.
The runtime continues to Finalize objects during shutdown only while the number of finalizable objects continues to decrease.