5

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?

1 Answer 1

5

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.

1
  • 1
    I'd already tried something like that (the string "Restart" has to be passed), and it seems to work, but I like passing the process ID. That way a user can't spoof a restart. Commented Dec 14, 2012 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.