簡體   English   中英

從啟動的過程中逐行獲取輸出

[英]Getting line by line output from a started process

我正在嘗試檢索由我啟動的進程生成的輸出行,這是代碼

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (myData singleJob in e.Argument as List<myData>)
    {
        ProcessStartInfo psi = new ProcessStartInfo("myCommandLineProgram.exe");
        psi.Arguments = "\"" + singleJob.row + "\"";
        psi.CreateNoWindow = true;
        psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.UseShellExecute = false;
        Process p = new Process();
        p.StartInfo = psi;
        p.Start();
        StreamReader sr = p.StandardOutput ;
        string line;
        while ((line = sr.ReadLine()) != null )
        {
            this.Invoke((MethodInvoker)delegate
            {
                    richTextBox1.AppendText(sr.ReadLine() + Environment.NewLine);
                    richTextBox1.ScrollToCaret();   

            });
        }

        //StreamReader streamOutput = p.StandardOutput;
        //string content = streamOutput.ReadToEnd();   
        //this.Invoke((MethodInvoker)delegate
        //{
        //    richTextBox1.AppendText(content + Environment.NewLine);
        //});

        p.WaitForExit();
    }
}

盡管注釋掉的代碼始終有效(但是不能逐行解析),但是上面的代碼還是有問題的,確實有些行無法顯示在richtextbox中,而另一些則為空白。

謝謝

那不應該像

richTextBox1.AppendText(line + Environment.NewLine);

line而不是sr.ReadLine() )?

兩次調用readLine()將每隔第二行丟棄一次。

另外,由於您在委托中調用ReadLine ,因此無法控制何時進行讀取。 之間可能有多個ReadLines() (來自while行)。

請注意,您也不應使用line變量:此變量在循環中始終引用同一行變量,在執行AppendText時此變量可能包含新內容。 您應該在循環內引入一個新的局部變量,例如

 while ((line = sr.ReadLine()) != null )
 {
   var theLine = line;
   this.Invoke((MethodInvoker)delegate
   {
       richTextBox1.AppendText(theLine + Environment.NewLine);
       richTextBox1.ScrollToCaret();   
   });
 }

只是在這里更改而不是ReadLine() ,將line放進去。 您已經在while循環中閱讀了該行

string appendingLine = line;
this.Invoke((MethodInvoker)delegate
{
          richTextBox1.AppendText(appendingLine + Environment.NewLine);
          richTextBox1.ScrollToCaret();   

});

編輯: MartinStettner給的答案是更好的選擇。 可能存在在執行委托之前更改line的情況,因此某些行可能會丟失,而其他行可能會重復。 因此,我將根據馬丁的回答更改答案,我想指出的是,他應該是這一答案的功臣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM