重启当前进程C#

时间:2011-07-24 09:16:29

标签: c# .net process installer

我有一个内置了一些安装程序的应用程序我想重新加载与应用程序相关的所有内容我想重新启动该过程。我已经搜索并看到Application.Restart()并且它有缺点,并想知道什么是我需要的最佳方法 - 关闭流程并重新启动它。或者,如果有更好的方法重新初始化所有对象。

3 个答案:

答案 0 :(得分:5)

我会启动一个新实例然后退出当前实例:

private void Restart()
{
    Process.Start(Application.ExecutablePath);

    //some time to start the new instance.
    Thread.Sleep(2000);

    Environment.Exit(-1);//Force termination of the current process.
}

private static void Main()
{
    //wait because we maybe here becuase of the system is restarted so give it some time to clear the old instance first
    Thread.Sleep(5000);

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(...
}

编辑但是您还应该考虑添加某种互斥量,以便只允许应用程序的一个实例在时间运行,例如:

private const string OneInstanceMutexName = @"Global\MyUniqueName";

private static void Main()
{
    Thread.Sleep(5000);
    bool firstInstance = false;
    using (System.Threading.Mutex _oneInstanceMutex = new System.Threading.Mutex(true, OneInstanceMutexName, out firstInstance))
    {
        if (firstInstance)
        {
            //....
        }
     }
}

答案 1 :(得分:0)

在我的WPF应用程序(互斥锁的单个实例)中,我将Process.Start与ProcessStartInfo一起使用,它发送一个定时cmd命令来重启应用程序:

ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.GetCurrentProcess()+ "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
ShellView.Close();

该命令被发送到操作系统,ping暂停脚本2-3秒,此时应用程序已退出ShellView.Close(),然后ping再次启动它后的下一个命令。

注意:\"将引号放在路径周围,因为它有空格,cmd无法在没有引号的情况下处理。 (我的代码引用this answer

答案 2 :(得分:-1)

我认为开始一个新流程并关闭现有流程是最好的方法。通过这种方式,您可以在启动和关闭过程之间为现有流程设置一些应用程序状态。

This主题讨论了Application.Restart()在某些情况下可能无效的原因。

System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
// Set any state that is required to close your current process.
Application.Current.Shutdown();

或者

System.Diagnostics.Process.Start(Application.ExecutablePath);
// Set any state that is required to close your current process.
Application.Exit();
相关问题