1

I need to execute my console app for many files in a loop and update my GUI. When I execute my app for the first time everything is ok, GUI updates are done in realtime. But with every iteration, reading of console output get longer delay. After 3-4 files I get only few updates or no updates at all. Its not a problem with updating GUI, my dataraceivedevent doesn't fire up.

I can't understand why, because after every iteration I close and dispose my process.

This is the method that I execute in the for-loop.

public void execute(string arguments, string path)
    {
        Process myProcess = new Process();
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.StartInfo.FileName = path;
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.RedirectStandardOutput = true;
        myProcess.StartInfo.Arguments = arguments;
        myProcess.Start();
        myProcess.BeginOutputReadLine();
        myProcess.OutputDataReceived += new DataReceivedEventHandler(this.updateProgress);
        myProcess.WaitForExit();
        myProcess.CancelOutputRead();
        myProcess.OutputDataReceived -= updateProgress;
        myProcess.Close();
        myProcess.Dispose();

        if (progressBar1.InvokeRequired)
        {
            progressBar1.BeginInvoke(new Action(() =>
            {
                progressBar1.PerformStep();
            }));
        }
        else
        {
            progressBar1.PerformStep();
        }

        if (progressBar2.InvokeRequired)
        {
            progressBar2.BeginInvoke(new Action(() =>
            {
                progressBar2.Value = 100;
                progressBar2.Refresh();
            }));
        }
        else
        {
            progressBar2.Value = 100;
            progressBar2.Refresh();
        }

        if (this.InvokeRequired)
        {
            this.BeginInvoke(new Action(() =>
            {
                this.Text = " ";
            }));
        }
        else
        {
            this.Text = " ";
        }
        Thread.Sleep(500);

    }
4

2 回答 2

0

请在之后调用.BeginOutputReadLine();方法.OutputDataReceived += new DataReceivedEventHandler(...);

OutputDataReceived在您开始阅读之前可能正在发生事件(在您附加事件之前)

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx

喜欢:

    myProcess.OutputDataReceived += new DataReceivedEventHandler(this.updateProgress);
    myProcess.BeginOutputReadLine();
于 2012-10-18T08:27:50.113 回答
0

执行 100K 次后我遇到了同样的问题,最后一次myProcess.WaitForExit();花了这么多时间。相反,您可以使用另一个重载,它采用整数表示进程有多少毫秒的时间退出。 myProcess.WaitForExit(1000);

于 2012-10-18T08:56:42.737 回答