Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructors are not guaranteed to be called

Tags:

c#

.net

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?
like image 331
Jethro Avatar asked Jul 14 '11 11:07

Jethro


2 Answers

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

like image 161
Boas Enkler Avatar answered Oct 13 '22 00:10

Boas Enkler


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.

like image 42
svanryckeghem Avatar answered Oct 13 '22 00:10

svanryckeghem