重新启动当前进程C#

use*_*077 6 .net c# installer process

我有一个内部装有安装程序的应用程序,我想为此重新加载与该应用程序相关的所有内容。我搜索并看到了Application.Restart()及其缺点,并想知道什么是执行我所需的最佳方法-关闭进程并重新启动它。或者是否有更好的方法来重新初始化所有对象。

Jal*_*aid 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(...
}
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)

  • 如果您的第一个应用程序在内存中停留的时间较长(出于任何原因),直到您的第二个实例唤醒,它们都将退出。但是使用“Thread.Sleep”解决竞争条件并不是一个解决方案。我会对每次启动时挂起 5 秒的应用程序感到恼火。仅当您的服务器运行终端服务时,“Global\”前缀才会产生影响。 (2认同)

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)