我正在使用.NET和C#啓動進程並異步讀取它的輸出。我的問題是,在我的程序讀取輸出之前似乎有延遲。如果我在命令行上運行可執行文件,它會在開始運行時立即輸出。但是當我使用我的代碼運行它時,ReadOutput事件處理程序不會在Process退出之前調用。我想用它來提供進程輸出的實時視圖,所以我不想等待(幾分鐘),直到進程退出。異步讀取進程輸出時的延遲
下面是一些相關的代碼:
MyProcess = new Process();
MyProcess.StartInfo.FileName = command;
MyProcess.StartInfo.Arguments = args;
MyProcess.StartInfo.UseShellExecute = false;
MyProcess.StartInfo.RedirectStandardOutput = true;
MyProcess.StartInfo.RedirectStandardError = true;
MyProcess.StartInfo.RedirectStandardInput = true;
MyProcess.OutputDataReceived += new DataReceivedEventHandler(ReadOutput);
MyProcess.ErrorDataReceived += new DataReceivedEventHandler(ReadOutput);
if (!MyProcess.Start())
{
throw new Exception("Process could not be started");
}
try
{
MyProcess.BeginOutputReadLine();
MyProcess.BeginErrorReadLine();
}
catch (Exception ex)
{
throw new Exception("Unable to begin asynchronous reading from process";
}
這是我的事件處理程序:
private void ReadOutput(object sendingProcess, DataReceivedEventArgs outLine)
{
OutputBuilder.AppendLine(outLine.Data);
Console.WriteLine(outLine.Data);
Console.Out.Flush();
}
您正在使用相同的方法處理OutputData和ErrorData的異步事件。我不會這樣設計它。特別是因爲'OutputBuilder'成員(一個'StringBuilder',我假設?)正在被兩個線程不安全地訪問。我將它分成兩個方法,每個方法都記錄到一個單獨的'StringBuilder'實例。 – 2011-03-03 22:59:07
這裏沒有任何答案似乎解決了這個問題。我在這個過程早已過去的時候遇到了完全相同的問題,但這些流仍然以某種方式寫入。 – OSH 2014-08-13 14:23:51