Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Nahum Avatar asked Oct 22 '11 17:10

Nahum


3 Answers

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)
like image 102
Hans Passant Avatar answered Oct 28 '22 21:10

Hans Passant


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

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

like image 34
Vlad Avatar answered Oct 28 '22 23:10

Vlad


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.

like image 31
Henk Holterman Avatar answered Oct 28 '22 21:10

Henk Holterman