如何以编程方式重新启动单个实例应用程序

5

我的WPF程序使用SingleInstance.cs确保只有一个实例在运行,如果用户尝试通过双击快捷方式或其他方式重新启动它。然而,在我的程序中有一种情况需要重新启动它自己。这是我用来执行重新启动的代码:

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();

这通常情况下可行,但问题在于它并不总是奏效。我猜测在某些系统上,第一实例和创建的RemoteService尚未终止,这导致调用Process.Start( App.ResourceAssembly.Location );的进程终止。

以下是我的app.xaml.cs中的Main方法:

[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();
    }
}

如果程序是通过编程方式重新启动的,那么正确的做法是什么?我应该添加一个名为Restartingbool标记,在for循环中等待调用SingleInstance<App>.InitializeAsFirstInstance返回true吗?还是有更好的方法?

1个回答

5

有一件事可以做,就是在调用Process.Start时,向可执行文件传递一个参数,告诉它这是一个“内部重启”的情况。然后该进程可以通过等待更长时间来处理这个问题,以等待该进程退出。甚至可以告诉它进程ID或其他信息,以便知道要监视什么。


1
我已经尝试过类似的方法了(需要传递字符串“Restart”),而且似乎可以工作,但我更喜欢传递进程ID。这样用户就无法欺骗重启。 - Tony Vitabile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接