ReRegisterForFinalize SuppressFinalize real life example
-
11-02-2021 - |
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?
La 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)
Autres conseils
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.