如何等待进程启动?
我的申请需要等到特定流程开始。我正在这样做
while (Process.GetProcessesByName("someProcess").Length == 0)
{
Thread.Sleep(100);
}
有没有其他方法(更优雅)如何完成此任务,其功能类似于 WaitForExit()?感谢您的回答。
My application need to wait until specific process will be started. I am doing it this way
while (Process.GetProcessesByName("someProcess").Length == 0)
{
Thread.Sleep(100);
}
Is there any other way(more elegant) how to accomplish this, with functionality similar to WaitForExit()? Thanks for answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 ManagementEventWatcher 类。
具体来说,链接底部的代码示例向您展示了如何设置 ManagementEventWatcher 以在创建新进程时收到通知。
从 MSDN 代码示例复制的代码(可以进行一些清理):
编辑
添加了
TargetInstance.Name = 'someProcess'
过滤器的简化示例。Take a look at the ManagementEventWatcher class.
Specifically, the code example at the bottom of the link shows you how to setup a ManagementEventWatcher to be notified when a new process is created.
Code copied from MSDN code example (could stand a little cleanup):
Edit
Simplifed example with
TargetInstance.Name = 'someProcess'
filter added.据我所知,
Process
类中没有任何内容可以使其变得简单。如果您无法控制子流程中的源代码,那么您可能应该使用 Calgary Coder 提供的 WMI 解决方案。
如果您确实可以控制子流程中的代码,那么还有一些其他方法可以解决此问题。我已经使用了 WCF (使用 IPC 绑定), .Net 远程处理,以及 互斥体。
这些解决方案的优点是子流程必须选择加入。子进程可以自由等待,直到完成其启动初始化例程,然后再让父应用程序知道它已“准备好”。
每个链接中都有示例,可以帮助您开始解决此问题。如果您有兴趣使用特定的解决方案,并且遇到问题,请告诉我,我将发布该特定解决方案的一些示例代码。
As far as I know, there is nothing on the
Process
class that will make it simple.If you don't have control over the source code in the sub-process, then you should probably go with the WMI solution that Calgary Coder provided.
If you do have control of the code in the sub-process, then there are a few additional ways you can solve this problem. I have used WCF (using an IPC binding), .Net Remoting, and Mutex.
The advantage of these solutions is that the sub process has to opt into it. The sub process is free to wait until it has completed its startup initialization routines before letting the parent app know that it is "ready".
There are samples at each of those links that should give you a start on solving this problem. If you are interested in going with a specific one, and have problems, let me know and I'll post some sample code for that particular solution.