Reputation: 2485
I'm quite familiar with the System.Diagnostics.Process class. But, I'm wondering about how I can monitor a specific process (i.e. Check to see if it's running every XX mins/secs). I need to be able to checking whether a process is running and if it is, continue with initialising the rest of the program.
Thanks,
-Zack
Upvotes: 2
Views: 2520
Reputation: 51071
If you didn't start the process yourself, you get find the Process
object associated with a process by looking through the list returned by Process.GetProcessesByName(...)
or Process.GetProcesses(...)
Once you have the process, you can listen read its properties (including HasExited
) and (as Jon mentions in his response) if you set EnableRaisingEvents
you can listen to its events (including Exited
).
Upvotes: 4
Reputation: 49534
Something like this, maybe?
Process[] processlist = Process.GetProcesses();
bool found = false;
foreach (Process theprocess in processlist)
{
if(theprocess.ProcessName == "YourProcessName")
{
found = true;
break;
}
}
if (!found)
{
return;
}
Upvotes: -1
Reputation: 1499730
Checking if it's still running is easy: Process.HasExited
.
Rather than polling this periodically, however, you could set EnableRaisingEvents
to true, and attach a handler to the Exited
event.
EDIT: To answer the question in the comment about "fetching" the process - that depends on what you already know. If you know its process ID, you could use Process.GetProcessById
. If you only know its name, you would have to use Process.GetProcessesByName
and work out what to do if you get multiple results. If you don't know the exact name, you could use Process.GetProcesses
and look for whatever you do know about it. Those options are effectively in order of preference :)
Upvotes: 5