如何等待进程启动?

发布于 2024-11-18 16:20:41 字数 200 浏览 4 评论 0原文

我的申请需要等到特定流程开始。我正在这样做

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇纵 2024-11-25 16:20:41

查看 ManagementEventWatcher 类。

具体来说,链接底部的代码示例向您展示了如何设置 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();
  }

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):

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.

  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();
  }
凌乱心跳 2024-11-25 16:20:41

据我所知,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文