简体   繁体   中英

How to make sure that the process is still running so that I can kill it?

I have a Process that I want to Kill ; however sometimes this produces the InvalidOperationException that says that the process has already exited.

To prevent the exception, I tried to check whether the process exited:

if (!p.HasExited)
{
    p.Kill();
}

However, I still occasionally see the exception. Since the process is running in parallel with my code, I assume that the problem could be essentially a race condition, ie the process terminating inbetween the check and the Kill() call.

What is the proper way to kill a process without raising the said exception? Of course that I can try-catch around the code in question, but that just doesn't seem like the best way to solve this.

You wouldn't be able to fix this problem, because there is a built-in race condition: the process may be alive at the time when you call p.HasExited , but by the time when your program calls p.Kill() it could already have exited.

A separate process is inherently a concurrent entity, so you would need some form of synchronization in order to solve this race condition. However, this problem cannot be solved in situations when you do not own the code of the process in question, because there is no way to synchronize activities of your program that monitors the process in question and the process itself.

You should send the kill signal unconditionally, trap the specific exception, and move on.

The proper way is to attempt to exit the process and catch the exception. The process could have ended in the time between you checking and invoking the exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM