WaitForExit is a direct OS call to wait for a process handle to become a signal. When the process ends, WaitForExit ends. Kill is a direct call to TerminateProcess , which is killed without any questions. When used correctly, WaitForExit will return upon completion of Kill .
So there is another error in your code. Create a simpler reproduction and you will see that the problem disappears. The error is hidden in the complexity of your code.
Or, WaitForExit back, but you did not notice it. Or Kill never executed or never executed. Again, simplifying the code will reveal the problem. Can you wrap it on 5 lines? I doubt you can, but I will look again if you do.
Try the following:
Process p = Process.Start("notepad.exe"); Task.Factory.StartNew(() => { Thread.Sleep(1000); p.Kill(); }); p.WaitForExit();
Update:
In the comments, you pointed out that killing ping does work, but there is no way to kill your special process. The reason for this is usually not canceled. The Windows kernel supports processes until all IOs are completed. The good news is that the process will finally disappear and the code will not return after Kill . The bad news is that resource cleanup is not complete.
Now you need to make sure your code can move, although WaitForExit not returned. To do this, I installed ManualResetEvent after completing Kill . And instead of calling WaitForExit you will get a process handle using the Process.Handle property and wait for one of the two waiting devices to become a signal. See what WaitForExit does internally to see how you could implement this yourself (I would copy the ProcessWaitHandle class, which is internal).
A simpler solution would be to call WaitForExit(TimeSpan.FromMilliseconds(100)) in a loop and check the exited flag each time.
source share