重启当前进程C#

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

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

 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) { //.... } } } 

在我的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无法在没有引号的情况下处理。(我的代码引用了这个答案 )

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

该主题讨论了为什么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();