Jethro
Jethro

Reputation: 5916

Destructors are not guaranteed to be called

I came across the following quote "Desctructors are not guaranteed to be called." and this scares me a bit.

It goes on to say that even a try finally block can be interrupted, causing memory leaks. It does give a solution by either placing your code in CER (constrained execution region) or derive from the CriticalFinalizerObject.

My question is

  1. What are the tradoffs by using CriticalFinalizerObject, if any?
  2. Are their any cases were you found deriving from CriticalFinalizerObject was really usefull?
  3. Should I only worry about using this when I start running into Memory leaks?

Upvotes: 10

Views: 1391

Answers (4)

CodesInChaos
CodesInChaos

Reputation: 108800

Typically the differences between a normal finalizers and critical finalizers only become important on AppDomain unload. Since most unmanaged resources automatically go away on process unload you usually need only to worry about critical finalization if you want to unload AppDomains cleanly while keeping the process running.

Upvotes: 0

svanryckeghem
svanryckeghem

Reputation: 923

Regarding question #3: memory leaks would typically be caused by:

  • Unmanaged resources not being freed. For those, using IDisposable (with a fallback call to Dispose() in the finalizer) is the best approach.

  • References to managed objects that are maintained because other objects still point to them, even though they are supposed to be removed. IHMO, that's more a problem of code quality than a low-level issue with garbage collection.

Unless you run into actual memory leaks, you should not even worry about it, and not try to force any behavior.

Upvotes: 1

Leonard Brünings
Leonard Brünings

Reputation: 13222

I would suggest using the IDisposable interface for all resources that need to be destroyed, and use them in a using block.

Upvotes: 0

Boas Enkler
Boas Enkler

Reputation: 12557

Why are you relying on desctructors ? most of the time you don't have any need of them.

Perhaps have a look at IDisposeable and the Dispose Pattern.

Here some links that helpes me to understand this subject

-> Everybody thinks about garbage collection the wrong way

-> How To implement dispose Pattern

-> Implementing Finalize and Dispose to Clean Up Unmanaged Resources

Upvotes: 3

Related Questions