process.OutputDataReceived 的重复输出

问题描述 投票:0回答:2

我遇到重定向输出中重复内容的问题。

在我的表单中有两个按钮:运行和清除。

  public partial class BatchRun : Form
 {
  Process process = new Process();

   public BatchRun()
    {
        InitializeComponent();                         
    }

    private void RunBTN_Click(object sender, EventArgs e)
    {
        //initiate the process 
        this.process.StartInfo.FileName = sMasterBATname;
        this.process.StartInfo.UseShellExecute = false;
        this.process.StartInfo.CreateNoWindow = true;
        this.process.StartInfo.RedirectStandardOutput = true;
        this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
        this.process.StartInfo.RedirectStandardInput = true;
        this.process.Start();
        this.process.BeginOutputReadLine();
    }

public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
    {
        BeginInvoke(new MethodInvoker(() =>
                {
                    Label TestLBL = new Label();
                    TestLBL.Text = text.TrimStart();
                    TestLBL.AutoSize = true;
                    TestLBL.Location = new Point(10, CMDpanel.AutoScrollPosition.Y + CMDpanel.Controls.Count * 20);
                    CMDpanel.Controls.Add(TestLBL);
                    CMDpanel.AutoScrollPosition = new Point(10, CMDpanel.Controls.Count * 20);
                }));            
    }


private void ClearBTN_Click(object sender, EventArgs e)
    {           
        CMDpanel.Controls.Clear();                       
        this.process.CancelOutputRead();
        this.process.Close();
        this.process.Refresh();                                   
    }
 }

如果我只想运行一次流程,即流程完成后关闭表单,这非常有用。

但是,我需要允许用户重新运行相同的进程或运行新的进程,因此我添加了一个清除按钮来清除各种控件等。

我遇到的问题是,单击清除按钮后,我想再次单击运行按钮而不关闭,然后应该运行 sMAsterBAT 文件(CMD)。

StandardOutputHandler 似乎包含上一次运行的内容以及新运行的内容,导致我的 CMD 面板中出现重复的标签。

这是否存储在某种缓冲区中?如果是这样,我该如何清除它以便重新运行?

有人可以解释为什么会发生这种情况以及如何解决它吗?

process io-redirection redirectstandardoutput
2个回答
0
投票

与为我解决问题的工作人员交谈。太简单了哈哈

 private void ClearBTN_Click(object sender, EventArgs e)
  {           
    CMDpanel.Controls.Clear();                       
    this.process.CancelOutputRead();
    this.process.Close();
    this.process.Refresh();  
    this.process = new Process();  // this line resolved my issue!!                                 
   }

}


0
投票

已经6年了,但我找到了这个问题的答案。

if(string.IsNullOrEmpty(e.Data)) // You used outLine
{
   // Your Codes
}
© www.soinside.com 2019 - 2024. All rights reserved.