C# destructor and finalizer - guarentees?

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?
 
J

Jon Skeet [C# MVP]

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.
 
J

Jeff Louie

A finalizer may not run if an exception is thrown in the finalizer list.

Regards,
Jeff
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 
T

tstephan

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.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top