I have an app that has some installer inside I want to reload everything associated to the app therefor I want to restart the process. I\'ve searched and saw the Application
I would start a new instance and then exit the current one:
private void Restart()
{
Process.Start(Application.ExecutablePath);
//some time to start the new instance.
Thread.Sleep(2000);
Environment.Exit(-1);//Force termination of the current process.
}
private static void Main()
{
//wait because we maybe here becuase of the system is restarted so give it some time to clear the old instance first
Thread.Sleep(5000);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(...
}
Edit: However you should also consider adding some sort of mutex to allow only one instance of the application to run at time, Like:
private const string OneInstanceMutexName = @"Global\MyUniqueName";
private static void Main()
{
Thread.Sleep(5000);
bool firstInstance = false;
using (System.Threading.Mutex _oneInstanceMutex = new System.Threading.Mutex(true, OneInstanceMutexName, out firstInstance))
{
if (firstInstance)
{
//....
}
}
}
In my WPF application (single instance by a mutex), I use Process.Start with a ProcessStartInfo, which send a timed cmd command to restart the app:
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.GetCurrentProcess()+ "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
ShellView.Close();
The command is sent to the OS, the ping pauses the script for 2-3 seconds, by which time the application has exited from ShellView.Close(), then the next command after the ping starts it again.
Note: The \" puts quotes around the path, incase it has spaces, which cmd can't process without quotes. (My code references this answer)
I think starting a new process and closing the existing process is the best way. In this way you have the ability to set some application state for the existing process in between starting and closing processes.
This thread discusses why Application.Restart()
may not work in some cases.
System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
// Set any state that is required to close your current process.
Application.Current.Shutdown();
Or
System.Diagnostics.Process.Start(Application.ExecutablePath);
// Set any state that is required to close your current process.
Application.Exit();