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
2010-02-22 20:55:55
+1 I love the name.
Kevin Gale
2010-02-22 20:59:15
@Greg - But strangely named. I'd think they'd call it ExitFast() instead... but why quibble?
Nick
2010-02-22 21:07:10
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
2010-02-22 21:08:53
@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
2010-02-22 21:15:00
@R. Bemrose: Then this is not what I need. I just want to terminate the process silently.
Sly
2010-02-22 21:17:41
If executing finalizers is a problem for you, I would say your application really is damaged beyond repair.
Jonathan Allen
2010-02-22 21:21:51
@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
2010-02-22 21:38:14
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
2010-02-22 21:41:47
+1
A:
This appears to work in a simple app, but I haven't tried it with anything complex:
System.Diagnostics.Process.GetCurrentProcess().Kill();
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
2010-02-22 21:18:02