簡體   English   中英

如何等待將要啟動的進程?

[英]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 RemotingMutex

這些解決方案的優點是子進程必須選擇加入它。 子進程可以自由等待,直到它完成其啟動初始化例程,然后才讓父應用程序知道它已“准備好”。

每個鏈接都有示例,可以幫助您開始解決此問題。 如果您有興趣使用特定的解決方案並遇到問題,請告訴我,我將發布該特定解決方案的一些示例代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM