Question

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?

Was it helpful?

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)

OTHER TIPS

The implementation of IDisposable often requires SuppressFinalize: look here or here for the code.

I don't have a good example on ReRegisterForFinalize now.

You need ReRegisterForFinalize when resurrecting an instance. Resurrection (mentioned in the linked article) is the action of re-rooting an object from its destructor (finalizer).

That only moves the question to "when would you resurrect an object". In my answer to this question I speculated that a connectionpool or similar construct might use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top