views:

220

answers:

3

Hello. My understanding about this class is that you should use it when you want to be sure that the Finalizer(destructor) or 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?

+1  A: 

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.

Joel Coehoorn
Well, like 20min passed and it still didn't execute the code :P
devoured elysium
The garbage collector doesn't care how much time has passed. If no allocations are made, it won't run. So the important question is what your code did during those 20 minutes -- or whether the finalizer ran when you exited the application.
jalf
I opened the application, ctrl+alt+del'ed it.
devoured elysium
Actually, I simply closed it(now that I think of it), clicked in the X on a console application.
devoured elysium
+2  A: 

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

280Z28
Hmm, so seems CriticalFinalizerObject is not what I was looking at. Is there any way I can be certain that my Finalize method will be called, even if there's a ctrl+alt+del?
devoured elysium
If you are looking for reliable operations even if the OS crashes (power outage?), then you should look into transactional processing.
280Z28
I don't need that much, I only need to be able to run some code when the application is closed or ctrl+alt+del'ed.
devoured elysium
"End Process" ends the process. Whatever you wanted to run, it's too late.
280Z28
+1  A: 

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.

overslacked
Both seem to be forms related, in this case this was actually a Console Application.
devoured elysium