My code is causing high CPU usage in WMI Provider host (WmiPrvSE.exe)

1.6k Views Asked by At

I've build a project in C# which at some point has to listen to a other file opening and closing. The code i use actually works but somehow every time i run my project "WMI Provider Host" will go crazy with CPU usage. First run it will hit 50% usage and each time i restart my project it will go up by like 10% until it hits 100%. I am not sure if i did something wrong in my code.

I tried putting that function into a new, clean file only to find out the same results.

This is what it looks like:

using System;
using System.Threading;
using System.Management;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string startEventName = "InstanceCreationEvent";
            string stopEventName = "InstanceDeletionEvent";
            string processName = "notepad.exe";

            ListenForProcess(processName, startEventName, (sender, e) =>
            {
                Console.WriteLine("Process Started");
            });

            ListenForProcess(processName, stopEventName, (sender, e) =>
            {
                Console.WriteLine("Process Stopped");
            });

        }

        static void ListenForProcess(string processName,
        string eventName, EventArrivedEventHandler eventHandler)
        {

        string queryString =
        $@"SELECT TargetInstance
        FROM __{eventName}
        WITHIN 0.1
        WHERE TargetInstance ISA 'Win32_Process'
        AND TargetInstance.Name='{processName}'";

            using (var watcher = new ManagementEventWatcher(queryString))
            {
                watcher.EventArrived += eventHandler;
                watcher.Start();

                new Thread(() =>
                {
                    while (true)
                    {
                        watcher.WaitForNextEvent();
                    }
                }).Start();
            }
        }

    }
}

I'm not sure why this is bugging WMI with it's CPU usage.

Only reference added is "System Management".

Any one here having any suggestions or know why this is happening? Thanks!

1

There are 1 best solutions below

2
huysentruitw On

You should not mix Start() with WaitForNextEvent(). Probalby Start() will also start a background thread that waits for the same event, so mixing both approaches can cause weird side-effects.

So either:

Use EventArrived with Start() (async usage):

var watcher = new ManagementEventWatcher(queryString);
watcher.EventArrived += eventHandler;
watcher.Start();
...
watcher.Stop();

Or, use WaitForNextEvent (sync usage):

var watcher = new ManagementEventWatcher(queryString);
var event = watcher.WaitForNextEvent();
...
watcher.Stop();