StandardOutput.ReadToEnd()挂起[重复]

StandardOutput.ReadToEnd()挂起[重复],第1张

StandardOutput.ReadToEnd()挂起[重复]

提出的解决方案

BeginOutputReadLine()
是一种很好的方法,但是在诸如此类的情况下,它是不适用的,因为进程(某些情况下使用
WaitForExit()
)的退出要比异步输出完全完成早。

因此,我尝试同步实现它,发现解决方案是使用类中的

Peek()
方法
StreamReader
。我添加了检查
Peek() >-1
以确保它不是MSDN文章中描述的流的结尾,
最后它可以工作并停止挂起!

这是代码:

var process = new Process();process.StartInfo.CreateNoWindow = true;process.StartInfo.UseShellExecute = false;process.StartInfo.RedirectStandardOutput = true;process.StartInfo.RedirectStandardError = true;process.StartInfo.WorkingDirectory = @"C:test";process.StartInfo.FileName = "test.exe";process.StartInfo.Arguments = "your arguments here";process.Start();var output = new List<string>();while (process.StandardOutput.Peek() > -1){    output.Add(process.StandardOutput.ReadLine());}while (process.StandardError.Peek() > -1){    output.Add(process.StandardError.ReadLine());}process.WaitForExit();


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4931195.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存