How to programmatically restart a single instance application

My WPF program uses SingleInstance.cs to make sure that only one instance works if the user tries to restart it by double-clicking on a short segment to it or some other mechanism. However, there is something in my program that is needed to reboot. Here is the code I use to perform the restart:

App.Current.Exit += delegate( object s, ExitEventArgs args ) { if ( !string.IsNullOrEmpty( App.ResourceAssembly.Location ) ) { Process.Start( App.ResourceAssembly.Location ); } }; // Shut down this application. App.Current.Shutdown(); 

This works most of the time, but the problem is that it does not always work. I assume that on some systems the first instance and the created RemoteService are not yet completed, and this leads to the termination of the process called by calling Process.Start( App.ResourceAssembly.Location ); .

Here is the main method in my app.xaml.cs:

 [STAThread] public static void Main() { bool isFirstInstance = false; for ( int i = 1; i <= MAXTRIES; i++ ) { try { isFirstInstance = SingleInstance<App>.InitializeAsFirstInstance( Unique ); break; } catch ( RemotingException ) { break; } catch ( Exception ) { if ( i == MAXTRIES ) return; } } if ( isFirstInstance ) { SplashScreen splashScreen = new SplashScreen( "splashmph900.png" ); splashScreen.Show( true ); var application = new App(); application.InitializeComponent(); application.Run(); SingleInstance<App>.Cleanup(); } } 

What is the right way to get this code to allow a new instance to start if it restarts programmatically? Should I add a bool Restarting flag and wait in a for loop to call SingleInstance<App>.InitializeAsFirstInstance to return true? Or is there a better way?

+4
source share
1 answer

One thing that needs to be done is that when calling Process.Start, pass an argument to the executable, which says it is an “internal reload”. The process can then handle this, waiting for a longer period of time for the process to exit. You can even say it ProcessID or something else so that he knows what to watch.

+4
source

All Articles