Search code examples
c#.netgarbage-collectionsuppressfinalize

ReRegisterForFinalize SuppressFinalize real life example


I was just reading this article, “Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework”, by Jeffrey Richter, and I couldn't think of any real life sample for using ReRegisterForFinalize or SuppressFinalize.

Could anyone provide me with some examples?


Solution

  • A handful of places it gets used in the .NET framework, always a good place to look. Basic patterns are:

    • a disposed object gets reused. The Dispose() method has called SuppressFinalize so it needs to be re-registered (NativeWindow, RequestContextBase, TaskExceptionHolder class)
    • the finalizer failed and caught an exception. Little to do but to retry later. That code is wrapped with if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) to make sure that doing this makes sense (DynamicResolver and LoaderAllocatorScout class)
    • the object participates in a caching scheme and gets re-cached (OverlappedData class)