2013-07-10 65 views
6

在C#中我開始了需要2-3個小時才能完成的第三方應用程序。我需要Process的輸出來實時寫入控制檯。我已經完成了來自微軟網站的BeginOutputReadLine()RedirectStandardOutput的研究,但我的代碼仍然無法正常工作。C#實時顯示進程的輸出

目前我的代碼只顯示過程完成時的輸出。我不知道它出錯的地方。

static void Main(string[] args) 
{ 
    Process process; 
    process = new Process(); 
    process.StartInfo.FileName = "C:\\ffmbc\\ffmbc.exe"; 
    process.StartInfo.Arguments = "-i \\\\dssp-isi-t\\TMD\\B002C010_130520_R2R7.2398v5.mxf -an -vcodec libx264 -level 4.1 -preset veryslow -tune film -x264opts bluray-compat=1:weightp=0:bframes=3:nal-hrd=vbr:vbv-maxrate=40000:vbv-bufsize=30000:keyint=24:b-pyramid=strict:slices=4:aud=1:colorprim=bt709:transfer=bt709:colormatrix=bt709:sar=1/1:ref=4 -b 30M -bt 30M -threads 0 -pass 1 -y \\\\dss-isi-t\\MTPO_Transfer\\dbay\\B002C010_130520_R2R7.2398v5.mxf.h264"; 
    process.StartInfo.UseShellExecute = false; 
    process.StartInfo.CreateNoWindow = true; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); 
    process.StartInfo.RedirectStandardInput = true; 
    process.Start(); 
    process.BeginOutputReadLine(); 
    process.WaitForExit(); 
    process.Close(); 
} 

private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{ 
    string line; 
    line = (outLine.Data.ToString()); 
    Console.WriteLine(line); 
} 
+0

@Xeano不完全相同的問題,但是,是非常相似的。 – feralin

+1

這很正常,當您重定向輸出時,該過程將切換到緩衝輸出。如果它不會吐出很多文本,那麼該緩衝區不足以導致它被刷新。如果你無法修復程序的代碼,你無能爲力。 –

回答

6

process.WaitForExit(); 

將導致目前的方案要等到給定過程完成。這絕對不是你想要的;你可能想要開始這個過程,讓它異步運行,然後讓它告訴你它什麼時候結束。爲此,您需要使用process.Exited事件。

+0

當我刪除process.WaitForExit();控制檯在後臺運行進程然後關閉,它仍然不會顯示實時輸出。我是否允許來自'OutputHandler'方法的字符串? – user2475310

2

與我以前回答的問題類似,甚至可能是重複的。 請參閱:Pipe a stream to Debug.Write()

這裏距這就是我的答案(略有修改):

process.StartInfo.UseShellExecute = false; 
process.StartInfo.RedirectStandardOutput = true; 
process.OutputDataReceived += p_OutputDataReceived; 
process.Start(); 
process.BeginOutputReadLine(); 

然後,用於接收數據的事件處理程序。

void p_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    Console.Write(e.Data); 
} 

基本上,你只需要nix上的WaitForExit(),因爲這使你的程序掛起,直到該過程完成。

+1

以前的問題是什麼?提供一個鏈接。如果這只是回答這個問題,你的回答應該是評論,而不是回答。 –

+0

感謝您的建議@JimMischel,我會在我的答案中添加一個鏈接。很抱歉,如果我的回答不合適,我仍然經常困惑什麼時候提出答案,什麼時候回答。 – Gray