Home > Software engineering >  Correct approach to check if a list of processes are running
Correct approach to check if a list of processes are running

Time:11-03

I'm writing an app using C# for a user to log their time usage of programs. They can pick processes and they are stored in a database.

The app is currently using a timer at a 5 second interval to loop through every running process on the device using Diagnostics.Process.GetProcesses() and checking this list of names against the ones in the database.

Is this a reasonable way to go about this? Or would it be better to create a thread for each process in the database that listens for it to start using Win32Process.ProcessInfo.StartedEventHandler()?

CodePudding user response:

Any time you can avoid polling, you should.

On launch, you'll need to enumerate the processes to get the current system state. After this, you can you can monitor process creation using WMI: Is there a System event when processes are created?. You could even modify that query to include only the processes you care about.

Whenever you get a match (either on startup, or the WMI event), use the Diagnostics.process.GetProcesses() call, and attach an event handler to the Process.Exeted event: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.exited?view=net-5.0 to know when it closes.

  • Related