【问题标题】:C# Capturing the output of a process asynchronous is always null [duplicate]C#捕获异步进程的输出始终为空[重复]
【发布时间】:2017-11-30 20:04:57
【问题描述】:

目前我正在尝试捕获控制台应用程序的输出。 如果我使用StandardOutput.ReadToEnd() 方法,我可以正确捕获输出,但如果我使用OutputDataReceived,则永远不会调用该事件。

我的代码:

Process testProcess = new Process();
testProcess.StartInfo.FileName = "teste.exe";
testProcess.StartInfo.UseShellExecute = false;
testProcess.StartInfo.RedirectStandardOutput = true;
testProcess.StartInfo.RedirectStandardError = true;
testProcess.StartInfo.RedirectStandardInput = true;
testProcess.EnableRaisingEvents = true;

testProcess.Start();
StreamWriter myStreamWriter = testProcess.StandardInput;
myStreamWriter.Write("a"); // press any key to continue

// var output = testProcess.StandardOutput.ReadToEnd(); // this works all the times

StringBuilder output = new StringBuilder();
testProcess.OutputDataReceived += (sender, e) => {
  // never raised
  if (e.Data != null)
    output.AppendLine("'" + e.Data + "'");
};

testProcess.WaitForExit();
Console.WriteLine(output);

【问题讨论】:

  • 尝试使用Process.BeginOutputReadLine(); 也对文档进行谷歌搜索,如果我没记错的话,这应该启动一个异步进程

标签: c# asynchronous


【解决方案1】:

阅读documentation of OutputDataReceived,必须致电testProcess.BeginOutputReadLine()

您可能还必须在设置 OutputDataReceived 事件后调用 testProcess.Start(),就像示例一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2013-01-29
    • 2011-12-07
    相关资源
    最近更新 更多