Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restart my C# WinForm Application?

Tags:

c#

.net

Developing a C# .NET 2.0 WinForm Application. Need the application to close and restart itself.

Application.Restart(); 

The above method has proven to be unreliable.

What is a better way to restart the application?

like image 969
Adam Nofsinger Avatar asked Apr 22 '09 21:04

Adam Nofsinger


People also ask

Where is my restart button?

Android smartphones and tabletsPress and hold the phone's power button (generally on the top or right side of the device) for 1-2 seconds until the power options menu appears, then release the power button. Tap Restart or Power off on the menu.


1 Answers

A much simpler approach that worked for me is:

Application.Restart(); Environment.Exit(0); 

This preserves the command-line arguments and works despite event handlers that would normally prevent the application from closing.

The Restart() call tries to exit, starts a new instance anyway and returns. The Exit() call then terminates the process without giving any event handlers a chance to run. There is a very brief period in which both processes are running, which is not a problem in my case, but maybe in other cases.

The exit code 0 in Environment.Exit(0); specifies a clean shutdown. You can also exit with 1 to specify an error occurred.

like image 135
EMP Avatar answered Sep 30 '22 16:09

EMP