我将启动一个新实例,然后退出当前实例:
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(...
}
Run Code Online (Sandbox Code Playgroud)
编辑:但是,您还应该考虑添加某种互斥锁,以仅一次运行应用程序的一个实例,例如:
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)
{
//....
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*thJ -1
我认为启动新流程并关闭现有流程是最好的方法。通过这种方式,您可以在启动和关闭进程之间为现有进程设置一些应用程序状态。
该线程讨论为什么Application.Restart()在某些情况下可能不起作用。
System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
// Set any state that is required to close your current process.
Application.Current.Shutdown();
Run Code Online (Sandbox Code Playgroud)
或者
System.Diagnostics.Process.Start(Application.ExecutablePath);
// Set any state that is required to close your current process.
Application.Exit();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8009 次 |
| 最近记录: |