我有一个应用程序,里面有一些安装程序,我想重新加载与该应用程序相关的所有内容,因此我想重新启动该过程。我已经搜索并看到了 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)
{
//....
}
}
}
关于c# - 重新启动当前进程 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6805975/