Thursday, June 01, 2006

Exiting from .NET Application

There are 2 ways by which you can exit from an application.

They are
1) Application.Exit
2) Environment.Exit

If you are using VB.NET then you have one more option "End"

Difference between Application.Exit and Environment.Exit

Application.Exit
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. This is the call to use if you are running a WinForms application.

Environment.Exit(int)
Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.
As a general guideline, use "Application.Exit" call if you have called System.Windows.Forms.Application.Run or if it is a console application then call "Environment.Exit(int)".


What about "End"?

The End statement stops code execution abruptly, without invoking the Finalize method or any other Visual Basic code. Object references held by other programs are invalidated. The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms.

How to check my program is running using Message Loop?

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

If (System.Windows.Forms.Application.MessageLoop)
{// Use this since we are a WinForms appSystem.
Windows.Forms.Application.Exit();
}
Else
{
// Use this since we are a console appSystem.
Environment.Exit(1);
}

You can use Application.ExitThread() to exit only from the current thread.

0 Comments:

Post a Comment

<< Home