如何重新启动我的C#WinForm应用程序? [英] How do I restart my C# WinForm Application?

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

问题描述

开发一个C#.NET 2.0的WinForm的应用。需要应用程序关闭并重新启动本身。

Developing a C# .NET 2.0 WinForm Application. Need the application to close and restart itself.

Application.Restart();

以上方法被证明是不可靠的

什么是更好的方式来重新启动应用程序?

What is a better way to restart the application?

推荐答案

不幸的是你不能使用的Process.Start()开始的当前运行的进程的一个实例。按照的Process.Start()文档: 如果该进程已经在运行,没有额外的处理资源开始...

Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..."

此技术将在VS调试器正常工作(因为VS做某种魔力,导致的Process.Start思考的过程尚未运行),但会失败时,调试器下无法运行。 (请注意,这可能是操作系统特定的 - 我似乎记得,在我的一些测试中,它的工作无论是在XP或Vista,但我可能只是记住在调试器下运行它)

This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.)

这个技术是完全用在其上,我目前工作的项目最后程序员之一,我一直试图找到一种解决方法相当一段时间。到目前为止,我只找到了一个解决方案,它只是感觉又脏又缺憾给我:启动第2应用程序,等待在后台应用为先终止,然后重新启动第一应用。我敢肯定,这是可行的,但是,呸。

This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck.

编辑:使用第2应用程序的工作。所有我的第二个应用程序所做的是:

Using a 2nd application works. All I did in the second app was:

    static void RestartApp(int pid, string applicationName )
    {
        // Wait for the process to terminate
        Process process = null;
        try
        {
            process = Process.GetProcessById(pid);
            process.WaitForExit(1000);
        }
        catch (ArgumentException ex)
        {
            // ArgumentException to indicate that the 
            // process doesn't exist?   LAME!!
        }
        Process.Start(applicationName, "");
    }

(这是一个非常简单的例子,真正的code有很多健全检查,错误处理等)

(This is a very simplified example. The real code has lots of sanity checking, error handling, etc)

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

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