栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ProcessStartInfo挂在“ WaitForExit”上吗?为什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ProcessStartInfo挂在“ WaitForExit”上吗?为什么?

问题是如果您重定向

StandardOutput
和/或
StandardError
内部缓冲区可能已满。无论您使用什么顺序,都可能出现问题:

  • 如果您在读取
    StandardOutput
    过程之前等待该过程退出,则该过程可能会阻止尝试对其进行写入,因此该过程永远不会结束。
  • 如果从阅读
    StandardOutput
    使用ReadToEnd的,然后 你的 过程可以阻止如果过程永远不会关闭
    StandardOutput
    (例如,如果它永远不会终止,或者如果它被阻止写入
    StandardError
    )。

解决方案是使用异步读取来确保缓冲区未满。为了避免任何死锁并收集两者的所有输出

StandardOutput
StandardError
您可以执行以下操作:

编辑:请参阅下面的答案,以了解如果发生超时,如何避免 ObjectDisposedException

using (Process process = new Process()){    process.StartInfo.FileName = filename;    process.StartInfo.Arguments = arguments;    process.StartInfo.UseShellExecute = false;    process.StartInfo.RedirectStandardOutput = true;    process.StartInfo.RedirectStandardError = true;    StringBuilder output = new StringBuilder();    StringBuilder error = new StringBuilder();    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))    {        process.OutputDataReceived += (sender, e) => { if (e.Data == null) {     outputWaitHandle.Set(); } else {     output.AppendLine(e.Data); }        };        process.ErrorDataReceived += (sender, e) =>        { if (e.Data == null) {     errorWaitHandle.Set(); } else {     error.AppendLine(e.Data); }        };        process.Start();        process.BeginOutputReadLine();        process.BeginErrorReadLine();        if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout))        { // Process completed. Check process.ExitCode here.        }        else        { // Timed out.        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369277.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号