6

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?

Andy
  • 331
  • 2
  • 12
Nahum
  • 6,959
  • 12
  • 48
  • 69

3 Answers3

11

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)
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
3

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

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

Vlad
  • 35,022
  • 6
  • 77
  • 199
  • 1
    OK 'SuppressFinalize' looks pretty strait-forward, after reading those samples. prevent the costly finalize method to be called if I dipspoed the object by myself. – Nahum Oct 22 '11 at 17:43
1

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.

Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
  • I still have no idea when would I want to use `ReRegisterForFinalize ` – Nahum Oct 22 '11 at 18:16
  • 1
    In 'normal' application or library code you wouldn't. A ConnectionPool is a highly specialized piece of software. – H H Oct 22 '11 at 18:19