tags:

views:

133

answers:

3

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

+2  A: 

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 :)

Jon Skeet
What about fetching the actual process and see if it's running?
Zack
Thanks, I actually did a combination of yours and Daniel's solutions.
Zack
+1  A: 

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).

Daniel LeCheminant
A: 

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;
        }
John Gietzen
If you know the actual name, you may as well use GetProcessesByName...
Daniel LeCheminant