[英]How to wait for process that will be started?
我的应用程序需要等到特定进程启动。 我正在这样做
while (Process.GetProcessesByName("someProcess").Length == 0)
{
Thread.Sleep(100);
}
有没有其他方法(更优雅)如何实现这一点,其功能类似于 WaitForExit()? 感谢您的回答。
查看ManagementEventWatcher class。
具体来说,链接底部的代码示例向您展示了如何设置 ManagementEventWatcher 以在创建新进程时收到通知。
从 MSDN 代码示例复制的代码(可以稍微清理一下):
using System;
using System.Management;
// This example shows synchronous consumption of events.
// The client is blocked while waiting for events.
public class EventWatcherPolling
{
public static int Main(string[] args)
{
// Create event query to be notified within 1 second of
// a change in a service
WqlEventQuery query =
new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0,0,1),
"TargetInstance isa \"Win32_Process\"");
// Initialize an event watcher and subscribe to events
// that match this query
ManagementEventWatcher watcher =
new ManagementEventWatcher();
watcher.Query = query;
// times out watcher.WaitForNextEvent in 5 seconds
watcher.Options.Timeout = new TimeSpan(0,0,5);
// Block until the next event occurs
// Note: this can be done in a loop if waiting for
// more than one occurrence
Console.WriteLine(
"Open an application (notepad.exe) to trigger an event.");
ManagementBaseObject e = watcher.WaitForNextEvent();
//Display information from the event
Console.WriteLine(
"Process {0} has been created, path is: {1}",
((ManagementBaseObject)e
["TargetInstance"])["Name"],
((ManagementBaseObject)e
["TargetInstance"])["ExecutablePath"]);
//Cancel the subscription
watcher.Stop();
return 0;
}
}
编辑
添加了TargetInstance.Name = 'someProcess'
过滤器的简化示例。
var query = new WqlEventQuery(
"__InstanceCreationEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\" and TargetInstance.Name = 'someProcess'"
);
using(var watcher = new ManagementEventWatcher(query))
{
ManagementBaseObject e = watcher.WaitForNextEvent();
//someProcess created.
watcher.Stop();
}
据我所知, Process
class 上没有任何东西可以让它变得简单。
如果您无法控制子流程中的源代码,那么您可能应该使用 Calgary Coder 提供的 WMI 解决方案 go。
如果您确实可以控制子流程中的代码,那么还有一些其他方法可以解决此问题。 我使用过WCF (使用IPC 绑定) 、.Net Remoting和Mutex 。
这些解决方案的优点是子进程必须选择加入它。 子进程可以自由等待,直到它完成其启动初始化例程,然后才让父应用程序知道它已“准备好”。
每个链接都有示例,可以帮助您开始解决此问题。 如果您有兴趣使用特定的解决方案并遇到问题,请告诉我,我将发布该特定解决方案的一些示例代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.