Note that there are some explanatory texts on larger screens.

plurals
  1. POcapture process stdout and stderr in the correct ordering
    text
    copied!<p>I launch a process from C# as follows:</p> <pre><code>public bool Execute() { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = "the command"; startInfo.FileName = "C:\\MyApp.exe"; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; Log.LogMessage("{0} {1}", startInfo.FileName, startInfo.Arguments); using (Process myProcess = Process.Start(startInfo)) { StringBuilder output = new StringBuilder(); myProcess.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { Log.LogMessage(Thread.CurrentThread.ManagedThreadId.ToString() + e.Data); }; myProcess.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { Log.LogError(Thread.CurrentThread.ManagedThreadId.ToString() + " " + e.Data); }; myProcess.BeginErrorReadLine(); myProcess.BeginOutputReadLine(); myProcess.WaitForExit(); } return false; } </code></pre> <p>But this has a problem... if the app in question writes to std out and std err in this order:</p> <pre><code>std out: msg 1 std err: msg 2 std out: msg 3 </code></pre> <p>Then the output I see from the logs is:</p> <pre><code>msg 2 msg 1 msg 3 </code></pre> <p>This seems to be because the event handlers are executed in another thread. So my question is how can the order of the process writing to std err and std out be maintained? </p> <p>I thought of using a time stamp but I don't think this will work due to the preemptive nature of threads..</p> <p>Update: Confirmed that using a time stamp on the data is no use.</p> <p>Final update: The accepted answer solves this problem - however it does have one drawback, when the streams are merged there is no way to know which stream was written to. Hence if you require the logic of write to stderr == failure rather than the app exit code you might still be screwed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload