我的应用程序需要等到特定进程开始.我是这样做的
while (Process.GetProcessesByName("someProcess").Length == 0) { Thread.Sleep(100); }
有没有其他方式(更优雅)如何实现这一点,功能类似于WaitForExit()?谢谢你的回答.
解决方法
看看
ManagementEventWatcher课程.
具体来说,链接底部的代码示例显示了如何设置ManagementEventWatcher以在创建新进程时收到通知.
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,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,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","TargetInstance isa \"Win32_Process\" and TargetInstance.Name = 'someProcess'" ); using(var watcher = new ManagementEventWatcher(query)) { ManagementBaSEObject e = watcher.WaitForNextEvent(); //someProcess created. watcher.Stop(); }