Catch Process Output Inside Exited EventHandler

27 Views Asked by At

I'm working on an application that spawns processes that perform jobs based on a schedule. The processes sometimes are being immediately terminated (possibly issue with AV). I need to capture the output from the process, hoping to find a stack trace that might be getting lost due to the termination.

The application spawns the processes and does not wait for them. I had an idea of using the Exited event handler and enabling redirection of output. Here's what I have so far:

var scheduledProcess = new Process();

var processStartInfo = new ProcessStartInfo
{
    FileName = WorkerPath,
    CreateNoWindow = true,
    UseShellExecute = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

scheduledProcess.StartInfo = processStartInfo;
scheduledProcess.EnableRaisingEvents = true;

scheduledProcess.Exited += (object sender, EventArgs e) =>
{
    var process = sender as Process;

    var details = process.StandardOutput.ReadToEnd() + " - Error: " + process.StandardError.ReadToEnd();

    // [Do some logging here with the details variable, etc ...]
};

scheduledProcess.StartInfo.Arguments = "0, 1"
scheduledProcess.Start();

I have a suspicion that I am deadlocking the application where I am using ReadToEnd(). It is important that I can still spawn the processes, capture and do something with the output without blocking the application. I am out of ideas at this point, I am beginning to wonder whether this is possible at all.

Many thanks for any help.

0

There are 0 best solutions below