Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(.net) CriticalFinalizerObject - What does it really do?

My understanding about this class is that you should use it when you want to be sure that the Finalizer (destructor) of the class is called, but from a couple of tests I did, it doesn't seem to be true. If it does not make sure that the dispose method is called, is there any other way of doing it? For example, if I want to make sure that some code is run to end my object, even if I close my program via Task Manager or something?

like image 244
devoured elysium Avatar asked Jul 21 '09 03:07

devoured elysium


3 Answers

Chris Brumme has explained this topic in a way I'm not sure could ever be topped. :)

like image 93
Sam Harwell Avatar answered Oct 12 '22 23:10

Sam Harwell


from a couple of tests I did, it doesn't seem to be true.

Finalizers in .Net are non-deterministic. That means there's no guarantee exactly when the finalizer will be called. Just because an object went out of scope or even was disposed, doesn't mean the finalizer will be called right away. The garbage collector will get around to it at some unknown time in the future.

like image 32
Joel Coehoorn Avatar answered Oct 12 '22 23:10

Joel Coehoorn


If you really need code to run when when your program is Ctrl+Alt+Del'd, I don't think there's any other way than to have a separate program that monitors the first's state. If you really need that much architecture, I think you'd want to be using a service and some client apps, or a pair or services.

This is assuming, though, that you've already looked into the Application events. If you haven't, check out this overview.

EDIT Better than that overview, probably, is the ApplicationExit event.

like image 21
overslacked Avatar answered Oct 12 '22 23:10

overslacked