Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait till process is no longer running OR until timeout has passed, whichever happens first

Tags:

c#

.net

timeout

I want to kill a process running on the machine using taskkill if they're still running after X seconds (a windows service was stopped but it takes time for processes to dissapear) What's the most correct way to accomplish the above in C# (.net 2.0 or possibly 3.0)?

I've utility method for verifying whether a process is still running, given the process name (using Process.GetProcesses()). (As the process is not spawned by my code, I can't use WaitTillExit to know when it's no longer running)

PS: the process runs on a remote machine

like image 929
akapulko2020 Avatar asked Aug 19 '10 09:08

akapulko2020


3 Answers

In fact, you can use Process.WaitForExit().

Simply get the process to wait for via

Process p = Process.GetProcessById(iYourID);

And then call

if(!p.WaitForExit(iYourInterval))
{ 
    p.Kill();
}

You can also get processes via their name by

Process.GetProcessesByName(strYourProcessName);
like image 182
Emiswelt Avatar answered Oct 20 '22 02:10

Emiswelt


You could call Process.WaitForExit, passing the appropriate timeout. This way you won't need to use your own check to see whether the process is still running.

like image 12
Tim Robinson Avatar answered Oct 20 '22 02:10

Tim Robinson


Process p = ...

bool exited = p.WaitForExit(10000); // 10 seconds timeout
like image 12
Thomas Levesque Avatar answered Oct 20 '22 02:10

Thomas Levesque