简体   繁体   English

如何等待将要启动的进程?

[英]How to wait for process that will be started?

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()?有没有其他方法(更优雅)如何实现这一点,其功能类似于 WaitForExit()? Thanks for answers.感谢您的回答。

Take a look at the ManagementEventWatcher class.查看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.具体来说,链接底部的代码示例向您展示了如何设置 ManagementEventWatcher 以在创建新进程时收到通知。

Code copied from MSDN code example (could stand a little cleanup):从 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;
    }
}

Edit编辑

Simplifed example with TargetInstance.Name = 'someProcess' filter added.添加了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();
  }

As far as I know, there is nothing on the Process class that will make it simple.据我所知, Process class 上没有任何东西可以让它变得简单。

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.如果您无法控制子流程中的源代码,那么您可能应该使用 Calgary Coder 提供的 WMI 解决方案 go。

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 .我使用过WCF (使用IPC 绑定、.Net RemotingMutex

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.如果您有兴趣使用特定的解决方案并遇到问题,请告诉我,我将发布该特定解决方案的一些示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM