views:

122

answers:

3

In our app, we have a quite extensive exception handling mechanism. At some point in our error handling logic, we want to terminate the application -- right at this point with no further code execution. Our current code use Environment.Exit() to do that. After a call to Environment.Exit(), some code is still executed. For instance, the GC may execute the finalizer of some objects (and that causes a problem in our case). We don't want that to happen. Is there a way to really kill our own process (a win32 API call maybe)? Of course we don't want the end-user to see the Windows dialog that appears when a program crashes...

+2  A: 

Use the Environment.FailFast method:

Terminates a process but does not execute any active try-finally blocks or finalizers.

Andrew Hare
+3  A: 

Try Environment.FailFast

Nick
+1 I love the name.
Kevin Gale
@Greg - But strangely named. I'd think they'd call it ExitFast() instead... but why quibble?
Nick
The doc says FailFast writes to the event log and creates a dump of the application! That is a lot of side effects. I don't think I'll be able to use that.
Sly
@Sly: Of course it does, this method is only supposed to be used "if the state of your application is damaged beyond repair."
R. Bemrose
@R. Bemrose: Then this is not what I need. I just want to terminate the process silently.
Sly
If executing finalizers is a problem for you, I would say your application really is damaged beyond repair.
Jonathan Allen
@Jonathan Allen: It is indeed. But I already know that that point. I don't need to write to the event log or create a memory dump. We have our own unhandled exception reporting mechanism.
Sly
When the GC finalizes the application's MainForm, that form's Dispose() method is called (by it's finalizer). Disposing a Form causes a long sequence of disposal of inner components. There is no way to guaranty that they will all successfully dispose without raising an exception. If an exception is raised after Environment.Exit() has been called, the AppDomain.CurrentDomain.UnhandledException is not raised and the application crashes and the end-user sees the Windows dialog that appears when a program crashes. That is what I'm trying to avoid.
Sly
+1  A: 

This appears to work in a simple app, but I haven't tried it with anything complex:

System.Diagnostics.Process.GetCurrentProcess().Kill();

GetCurrentProcess:

Gets a new Process component and associates it with the currently active process.

Kill:

Kill forces a termination of the process, while CloseMainWindow only requests a termination.

R. Bemrose
I'll try that in our context. I'll be back with the results...
Sly
@R. Bemrose: I confirm that this works in my app too. Thank you.
Sly