重新启动当前进程的C# [英] Restarting current process C#

查看:179
本文介绍了重新启动当前进程的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,有一些安装程序里面我要重新加载相关的应用程序为此我要重新启动过程中的一切。我搜索,看到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)
        {
            //....
        }
     }
}

这篇关于重新启动当前进程的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆