Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliably Restart a Single-Instance WPF application

Tags:

wpf

restart

I would like to have my current application close and restart. I have seen many posts on this, however none of these seem to work for me.

I have tried

 System.Diagnostics.Process.Start(System.Windows.Application.ResourceAssembly.Location);
 System.Windows.Application.Current.Shutdown();

However this only restarts the application once. If I press my 'restart' button again (on the already restarted app), it only closes.

I have also tried launching a new System.Diagnostics.Process and closing the current process, but again this does not restart, it simply closes.

How can I restart my current WPF application?

like image 761
lost_bits1110 Avatar asked Nov 04 '22 12:11

lost_bits1110


1 Answers

You could create another application which you start when exiting your app and which in return does start your application again. Kind of like how a patcher would work, only without patching anything. On the plus side you could have a loop in that "restart-application" which checks all running processes for your main application process and only tries to re-start it once it does not appear in the process any longer - and you got the bare bones for a patcher also :) Whilst you do not seem to have a problem with restarting your application due to it still being in the processlist - it is the way I would go for when doing it in a production environment as this gives you the most control IMHO.

Edit:

That part in the button event handler (or wherever you want to restart your app with) of your main app (Process2BRestarted.exe in my case):

    private void cmdRestart_Click(object sender, EventArgs e)
    {
        var info = new ProcessStartInfo();

        info.FileName = "ProcessReStarter";
        info.WindowStyle = ProcessWindowStyle.Hidden;
        Process.Start(info);

        Application.Exit();
    }

This should go into your utility/restarter application (ProcessReStarter.exe over here):

    private void MainForm_Load(object sender, EventArgs e)
    {
        // wait for main application process to end
        // really should implement some kind of error-checking/timer here also
        while (Process.GetProcessesByName("Process2BRestarted").Count() > 0) { }
        // ok, process should not be running any longer, restart it
        Process.Start("Process2BRestarted");
        // and exit the utility app
        Application.Exit();
    }

Clicking the restart button will now create a new process ProcessReStarter.exe, which will iterate through the process list of all running processes - checking whether Process2BRestarted is still running. If the process does not appear in the list (any longer) it will now start a new Process2BRestarted.exe process and exit itself.

like image 96
Sascha Hennig Avatar answered Nov 14 '22 23:11

Sascha Hennig