How to forcibly close Process in c# after some period of time?

I got following code

    System.Diagnostics.Process capp = new System.Diagnostics.Process();
    capp.StartInfo.UseShellExecute = false;
    capp.StartInfo.RedirectStandardOutput = true; 
    capp.StartInfo.RedirectStandardError = true;
    capp.EnableRaisingEvents = false;
    capp.StartInfo.FileName = "app.exe";
    capp.StartInfo.Arguments = "-i -v -mj";

    consoleOutput = capp.StandardOutput.ReadToEnd() + capp.StandardError.ReadToEnd();
    if (!capp.WaitForExit(10000)) capp.Kill(); 

and problem, if outside application works correctly it takes less than 10 seconds for it to complete its tasks. If it stop/hung for some reason despite of using

    if (!capp.WaitForExit(10000)) capp.Kill(); 

as suggested in some other topic, it keeps working. Above line seem not to work at all in my case, i guess it has to do with fact i read StandardOutput and StandardError. How to fix my code to make reading output and WaitForExit() to work aside?


If you don't always read from both StandardOutput and StandardError the buffers can fill causing the process to block.

You first try to read StandardOutput to the end. The process you run might be writing a lot of data to StandardError until it blocks and can't write more. Then this results in your application blocking as it doesn't even start reading from StandardError until the process closes its StandardOutput. This creates a deadlock and neither process will continue.

I suggest you use the solution I've posted here. It uses asynchronous reads to read from both StandardOutput and StandardError, avoiding deadlocks.

Need Your Help

Override MailChimp stylesheet with second stylesheet

html css mailchimp

Goal: change background color of "Subscribe" button on MailChimp embedded sign-up form on company website page

PdfBox - probem with encoding in extracted text

c# pdf encoding pdfbox

Some PDF contains text with "strange" encoding.