My WPF program uses SingleInstance.cs to make sure that only one instance of it is running if a user tries to restart it by double clicking a short cut to it or some other mechanism. However, there is a circumstance in my program where it needs to restart itself. Here's 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 it doesn't always work. My guess is that on some systems, the first instance and the RemoteService
it creates haven't terminated yet and this causes the process started by the call to Process.Start( App.ResourceAssembly.Location );
to terminate.
Here's 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's the right way to get this code to allow a new instance to start if it's being restarted programmatically? Should I add a bool
flag Restarting
and wait in the for
loop for the call to SingleInstance<App>.InitializeAsFirstInstance
to return true? Or is there a better way?
The easiest way to restart an application in C# is to use the Application. Restart() function. The Application. Restart() function is used to restart an application in C#.
A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.
One thing to do would be that when you call Process.Start, pass an argument to the executable telling it that it is an "internal restart" situation. Then the process can handle that by waiting for a longer period of time for the process to exit. You could even tell it the ProcessID or something so it knows what to watch for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With