Sylvain
Sylvain

Reputation: 19259

How to immediately exit a Windows Forms .NET application?

In our application, 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...

Upvotes: 4

Views: 807

Answers (3)

Powerlord
Powerlord

Reputation: 88796

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.

Upvotes: 2

Nick
Nick

Reputation: 5955

Try Environment.FailFast

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351516

Use the Environment.FailFast method:

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

Upvotes: 5

Related Questions