Process.WaitForExit 方法在 Process.Close 后引发 InvalidOperation 异常

发布于 2024-11-26 13:50:44 字数 680 浏览 6 评论 0原文

我正在开发一个依赖于监视服务(以 Windows 服务的形式)的项目,该服务检查来自主服务的简单 TCP 心跳。每当一段时间内没有检测到心跳,或者根本没有检测到主服务进程时,它就会启动一个新的心跳。为了确保一次只有一个主服务在运行,它还会在启动新实例之前关闭所有当前正在运行的同名进程。

我遇到的问题源于以下代码:

 var processes = from p in Process.GetProcessesByName("Acme") select p;

 foreach (var process in processes)
 {
     ...

     process.Close();

     process.WaitForExit(10000);
     if (!process.HasExited)
         process.Kill();
 }

因为 process.Close() 方法释放了与该进程关联的所有资源,所以 WaitForExit() 方法引发了异常。我不想立即 Kill() 进程,因为我希望清理方法在关闭时在主服务中触发。

我的问题的解决方案是调用 process.CloseMainWindow() 代替 process.Close() ,它调用所有关联的清理方法,并且直到 WaitForExit() 方法之后才释放资源。

如果这个问题有更优雅的解决方案,请告诉我。

I am working on a project which relies on a monitoring service (in the form of a windows service) which checks for a simple TCP heartbeat from the main service. Whenever a heartbeat is not detected for a certain time period, or no main service process is detected at all, it fires up a new one. To ensure that only one main service is running at a time, it also will close all currently running process by the same name before starting the new instance.

The problem I was having stemmed from the following code:

 var processes = from p in Process.GetProcessesByName("Acme") select p;

 foreach (var process in processes)
 {
     ...

     process.Close();

     process.WaitForExit(10000);
     if (!process.HasExited)
         process.Kill();
 }

Because the process.Close() method released all resources associated with that process, the WaitForExit() method threw an exception. I didn't want to just Kill() the process straight away as I wanted the cleanup methods to fire in the main service on close.

The solution for my problem was to call process.CloseMainWindow() in the place of process.Close() which called all of the associated clean up methods and did not release the resources until after the WaitForExit() method.

If there is a more elegant solution to this problem, please let me know.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜无邪 2024-12-03 13:50:44

Process.Close 不会终止实际进程。对进程完全没有影响;它只是释放 Process 类的资源(之后它就不再可用,正如您所发现的)

如果您的目的是结束进程,则必须使用另一种方法,例如 Process。 Kill 或 Process.CloseMainWindow

Process.Close 有不同的用途;您应该在完成 Process 类实例后调用它(或 Process.Dispose)。

Process.Close doesn't terminate the actual process. It has no effect on the process at all; it just releases the resources of the Process class (after which it is no longer usable, as you discovered)

If your intention is to end the process, you must use another method such as Process.Kill or Process.CloseMainWindow.

Process.Close has a different use; you should call that (or Process.Dispose) after you are done with the Process class instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文