【问题标题】:In C#, how can I get the output of a process as string while also terminating process if taking too long? [duplicate]在 C# 中,如果花费太长时间,如何将进程的输出作为字符串同时终止进程? [复制]
【发布时间】:2018-06-12 21:40:12
【问题描述】:

以下代码未能超时。即使我必须关闭它,我也想读取进程的输出。

var proc = new Process
{
 StartInfo = new ProcessStartInfo
{
 FileName = '"' + filepath + '"',
Arguments = execArgs,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};

proc.Start();
string poutput = proc.StandardOutput.ReadToEnd();
bool bl = proc.WaitForExit(0 * 60 * 1000);

【问题讨论】:

  • 查看其他类似问题;你只想异步读取它而不是使用同步的ReadToEnd

标签: c# process


【解决方案1】:

你可以使用OutputDataReceived事件

StringBuilder sb = new StringBuilder();
proc.OutputDataReceived += (x,s) => sb.AppendLine(s.Data);

proc.Start();
proc.BeginOutputReadLine();

proc.WaitForExit(0 * 60 * 1000);
var output = sb.ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2014-07-29
    • 2015-11-28
    • 2017-01-27
    • 2017-03-03
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多