重新启动当前进程的C#重新启动、进程

2023-09-03 01:38:32 作者:奶思兔米鱿

我有一个应用程序,有一些安装程序里面我要重新加载相关的应用程序为此我要重新启动过程中的一切。我搜索,看到Application.Restart(),它的缺点,不知道什么是做什么,我需要的最佳途径 - 关闭进程,并重新启动它。或者有什么更好的办法来重新初始化的对象。

I have an app that has some installer inside I want to reload everything associated to the app therefor I want to restart the process. I've searched and saw the Application.Restart() and it's drawbacks and wondered what's the best way to do what I need - closing the process and restarting it. or if there's any better way to reinitialize all objects.

推荐答案

我将开始一个新的实例,然后退出当前的:

I would start a new instance and then exit the current one:

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(...
}

编辑:但是你也应该考虑增加某种互斥允许应用程序只有一个实例在运行的时候,像:

However you should also consider adding some sort of mutex to allow only one instance of the application to run at time, Like:

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