Take the 2-minute tour ×

I'm having a bit of trouble de-ciphering the msdn documentation.

I want to call the process class. If the process that the process class calls exits I want my code to exit but I want the "StandardOutput" and the "StandardError" to be written to a log file.

If the process that the process class calls hangs (and doesnt exit) I want my code to timeout and close the process after a certain timeout 'time' but I still want the "StandardOutput" and the "StandardError" to be written to a log file.

So I have this as my code:

using (Process p = new Process())
    p.StartInfo.FileName = exePathArg;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.Arguments = argumentsArg;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;


        StreamReader standardOutput = p.StandardOutput;
        StreamReader standardError = p.StandardError;

        retDirects.Add("StandardOutput", standardOutput.ReadToEnd());
        retDirects.Add("StandardError", standardError.ReadToEnd());    
    catch (Exception ex)
        //nothing to do with this yet
        catch { }

Is this the right way of doing things?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Not exactly, you need a timer to set the timeout. This code might help you:

Process process = Process.Start(startInfo);

process.EnableRaisingEvents = true;

bool execTimeout = false;

// this call back will be called when timer ticks, Timeout for process.
TimerCallback callBack = (_process) =>
    // if the process didn't finish exexuting
    // and the timeout has reached 
    // then kill the process.
    if (!(_process as Process).HasExited)
        execTimeout = true;
        (_process as Process).Kill();

int timeout = 4000; // 4 seconds
System.Threading.Timer timer = new System.Threading.Timer(callBack, 
                                     process, timeout, Timeout.Infinite);

// block untill finishing executing [Sync calling]

// Disable the timer. because the process has finished executing.
timer.Change(Timeout.Infinite, Timeout.Infinite);

// if the process has finished by timeout [The timer which declared above]
// or finished normally [success or failed].
if (execTimeout)
    // Write in log here
    string standardOutput = process.StandardOutput.ReadToEnd();
    string standardError = process.StandardError.ReadToEnd();

Good luck!

share|improve this answer
I dont understand this code :-(, I have no idea what line 8 means. Is that an anonymous method? –  Exitos Apr 12 '11 at 10:08
Well, you can make it as a normal function. Just take it out. –  Homam Apr 12 '11 at 11:50
add comment

Your Answer


