Process.HasExited property does not work as expected

G

Guest

I've created a windows service to ensure another service is running. First of
all, I look for the process relative to the service I'm monitoring. The code
is:

Process[] processes = Process.GetProcesses();
foreach(Process process in processes)
if(!process.HasExited &&
process.Id > 0 &&
process.ProcessName.ToLower() != "system" &&
process.MainModule.FileName.ToLower() ==
serviceDetail.ExecutablePath.ToLower())
...

The problem is with the MainModule property, called at the end of the if
statement. Internally, the MainModule property gets all modules for the
process and looks for the main one. So, if the process has exited, the search
for the process modules fails and we get an exception.

In order to solve this issue, I test the HasExited property at first place.
However, I still get an exception: "Cannot process request because the
process (3248) has exited." Why this exception occurs if I have tested the
HasExited property? Am I doing somethig wrong or missing something?

Another exception is thrown too. Sometimes I get an "Access is denied"
exception from this code piece.

Does anyone have any idea that could help me?
Thanks in advance.

Ricardo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top