1

I am trying to write an automation software to execute certain things when different processes are started and then do another thing when they are closed.

I have successfully gotten this to work using ManagementEventWatcher. This, however, uses WMI in Windows, which in turn causes WMI Provider Host to use ~4% of the CPU. I find this to be a little excessive.

Is there a way to do what I want without the extreme CPU overhead?

Thanks

2
  • 2
    There are a couple ways. ManagementEventWatcher is a good decoupled fire-and-forget way to do it, but it can be a bit intensive. A less intensive but more "manual" way to do it would just be to get the list of processes every couple seconds and search for the process you're looking for. If you have access to the other program, the least intensive solution would be to send a message from the other program to your program indicating it's started, and pass the process ID. This can be done in a lot of ways. The most common are anonymous pipes (windows only) or TCP/UDP sockets. Commented Nov 9, 2022 at 22:37
  • @Jesse Thanks for the feedback! I unfortunately do not have access to the other program so any form of communication will not work. I was under the impression that getting all the processes and manually searching would increase my CPU usage. I was going to give that a try anyhow so I might as well try it and see how bad the overhead is. Thanks again! Commented Nov 9, 2022 at 23:01

1 Answer 1

1

The way I did this was actually opposite of my original plan.

Instead of listening for process starts/stops, or polling all the processes, I simply get all the processes with the desired exe name, if it exists, I do what I want. Here's some code snippet.

// All this goes into its own thread while (true) // I use a boolean variable instead of true, so I can close it later { Thread.Sleep(1000); foreach(string process in configuredProcesses) //configuredProcesses is a simple string list which contains the names of processes I am looking for { Process[] processes = Process.GetProcessesByName(process); if (processes.Length > 0) { // process exists, execute code } } } 

This approach now uses about 0.1% CPU for my process, a much better overhead than WMI.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.