0

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()?

Bent Tranberg
  • 3,445
  • 26
  • 35
  • 1
    If it works, and it's working well enough for your needs, then what's the problem? We're engineers, there is no such thing as a perfect solution. – gunr2171 Nov 02 '21 at 21:34
  • 1
    What is your requirement? Implement it in a way that your requirements are fulfilled – Thomas Weller Nov 02 '21 at 21:38
  • 1
    BTW: Running an EXE != using it. My PC has >200 EXEs running and I feel that I'm only using Firefox. I don't know what all the others do. – Thomas Weller Nov 02 '21 at 21:40
  • 1
    Running one thread per entry is definitely overkill. What if I have 1000 entries in the database? Will you run 1000 threads? This will result in uninstallation or bug reports – Thomas Weller Nov 02 '21 at 21:42
  • Yeah after thinking about it I'll stick with a timer for now as one thread per entry does seem a little much. My concern was that when the app is running in the background it may be using more resources than it has to, but I suppose I'll have to develop the app more to test its performance in that particular way. Thank you for your help! –  Nov 02 '21 at 22:13

1 Answers1

1

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://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.exited?view=net-5.0 to know when it closes.

Charlie
  • 8,530
  • 2
  • 55
  • 53
  • Process creation through WMI is what I needed, from there I can query using the names in my database. Thank you! –  Nov 02 '21 at 23:22