WMI进程监视使用过多的CPU!有更好的方法吗? [英] WMI Process Watching uses too much CPU! Any better method?

查看:123
本文介绍了WMI进程监视使用过多的CPU!有更好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要注意Windows机器上何时启动或停止了某些进程.我目前正在进入WMI系统并每5秒查询一次,但这会导致每5秒CPU峰值,因为WMI是WMI.有更好的方法吗?我可以列出正在运行的进程,然后通过System.Diagnostics命名空间将一个Exited事件附加到它们,但是没有用于创建的事件处理程序.

I need to watch when certain processes are started or stopped on a Windows machine. I'm currently tapped into the WMI system and querying it every 5 seconds, but this causes a CPU spike every 5 seconds because WMI is WMI. Is there a better way of doing this? I could just make a list of running processes and attach an Exited event to them through the System.Diagnostics Namespace, but there is no Event Handler for creation.

推荐答案

这并不是您在现实世界中的确切做法,但应该有所帮助.这似乎根本不会驱动我的CPU.

This is not exactly how you'd do it in the real world but should help. This seems not to drive my CPU much at all.

    static void Main(string[] args)
    {
        // Getting all instances of notepad
        // (this is only done once here so start up some notepad instances first)
        // you may want use GetProcessByPid or GetProcesses and filter them as required
        Process[] processesToWatch = Process.GetProcessesByName("notepad");

        foreach (var process in processesToWatch)
        {
            process.EnableRaisingEvents = true;
            process.Exited +=
                (s, e) => Console.WriteLine("An instance of notepad exited");
        }

        Thread watchThread = new Thread(() =>
            {
                while (true)
                {
                    Process[] processes = Process.GetProcesses();
                    foreach (var process in processes)
                    {
                        Console.WriteLine("{0}:{1}", process.Id, process.ProcessName);
                    }
                    // Don't dedicate a thread to this like I'm doing here
                    // setup a timer or something similiar
                    Thread.Sleep(2000);
                }
            });
        watchThread.IsBackground = true;
        watchThread.Start();

        Console.WriteLine("Polling processes and waiting for notepad process exit events");
        Console.ReadLine();
    }

这篇关于WMI进程监视使用过多的CPU!有更好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆