C# destructor and finalizer - guarentees?

  • Thread starter Thread starter tstephan
  • Start date Start date
T

tstephan

I remember reading a few years back about destructors not being
guarenteed to be run. Doing a search all I can find is a reference to
some bugs with finalizers and appdomains in 1.0 and 1.1. Are
destructors guarenteed to be called in every case? Are there any
pathological cases?
 
I remember reading a few years back about destructors not being
guarenteed to be run. Doing a search all I can find is a reference to
some bugs with finalizers and appdomains in 1.0 and 1.1. Are
destructors guarenteed to be called in every case? Are there any
pathological cases?

If you've got some finalizers which take a long time to run, others may
not get run as there's a time limit for running finalizers at the end
of an application process.
 
A finalizer may not run if an exception is thrown in the finalizer list.

Regards,
Jeff
 
I remember reading a few years back about destructors not being
guarenteed to be run. Doing a search all I can find is a reference to
some bugs with finalizers and appdomains in 1.0 and 1.1. Are
destructors guarenteed to be called in every case? Are there any
pathological cases?

Finalizers are not guaranteed to run, and it's not a bug.

There is no destructors in .NET. There are no reference counters.
Nothing happens when the last reference to an object goes out of scope.
The object will just stay in memory until the garbage collector collects it.

When the garbage collector finds an object that is not used and it has a
finalizer, it will be placed in the finalizing queue, where the
finalizer eventually will be called by a background thread.

If an object has not been collected when the application ends, or if
it's still in the finalizing queue, the finalizer will never run.
 
Yes, the C# syntax for finalizers is the old destructor syntax in C++.
Are the caveats for this documented on MSDN anywhere? I failed to find
a section discussing this.
 
Look up Garbage collection. There you will find the section "Developer
Backgrounds in Memory Management" that discusses the difference in
memory management between different platforms. You will also find other
information about memory management.
 
Back
Top