c# - 重新启动当前进程 C#

标签 c# .net process installation

我有一个应用程序,里面有一些安装程序,我想重新加载与该应用程序相关的所有内容,因此我想重新启动该过程。我已经搜索并看到了 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/

相关文章:

c# - 对象未沿所有执行路径放置

c# - Request ["xx"] 和 Request.Form ["xx"] 之间的区别?

C# - 将字节数组转换为结构数组,反之亦然(反向)

php - 如果 VTiger 使用 PHP,那么哪个 CRM 用于 Rails?

python - 如何知道正在运行的脚本是否死亡?

java - 执行后向Runtime.getRuntime().exec()发送参数

c# - 使用正则表达式从 AssemblyInfo.cs 文件中检索程序集版本

.Net - 更好的命名控制方式 - 匈牙利表示法或完整表示法,例如 lbl 或 Label

c# - Rx 中的高级历史流和实时流

linux - if 语句的计算结果始终为 TRUE