0

我正在尝试从 Process.StandardOutput 获取数据......但我有一个问题:我在进程结束时获取数据,但不是在执行期间(它不刷新???)。看起来数据缓冲在某处。当我手动运行该过程时,消息在执行期间出现。怎么修?

4

1 回答 1

0

这就是我用来从流程中获取输出的方法。这是添加到字符串生成器,但您可以做其他事情。

    private void RunWithOutput(string exe, string parameters, out string result, out int exitCode)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo(exe, parameters);
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardError = true;
        startInfo.RedirectStandardOutput = true;
        Process p = new Process();
        p.StartInfo = startInfo;

        p.Start();

        StringBuilder sb = new StringBuilder();
        object locker = new object();
        p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args) 
        {
            lock(locker)
            {
                sb.Append(args.Data);
            }
        } );
        p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args)
        {
            lock (locker)
            {
                sb.Append(args.Data);
            }
        });

        p.BeginErrorReadLine();
        p.BeginOutputReadLine();

        p.WaitForExit();
        result = sb.ToString();
        exitCode = p.ExitCode;
    }
于 2013-08-31T00:28:03.963 回答