You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6中为Process进程实现超时机制的方法

实现Process调用的超时功能

你可以通过Process.WaitForExit(int millisecondsTimeout)方法实现超时控制,该方法会等待进程退出,并在指定毫秒数后返回结果:返回true表示进程正常退出,false表示超时。超时后需要主动终止外部进程,避免资源占用。

修改后的代码如下:

static string ExternalExe(string input)
{
    string output = string.Empty;

    ProcessStartInfo info = new()
    {
        FileName               = "path_here",
        Arguments              = input,
        RedirectStandardOutput = true,
        UseShellExecute        = false,
        // 可选:如果外部程序可能输出错误信息,建议同时重定向StandardError并处理
        // RedirectStandardError = true,
        CreateNoWindow         = true // 避免弹出外部程序窗口
    };

    using (Process? process = Process.Start(info))
    {
        if (process == null)
        {
            throw new CustomException();
        }

        // 等待进程退出,超时时间设为1000毫秒(1秒)
        bool exitedWithinTimeout = process.WaitForExit(1000);

        if (!exitedWithinTimeout)
        {
            // 超时:终止外部进程
            process.Kill();
            throw new TimeoutException("外部程序执行超时");
        }

        // 进程正常退出后读取输出
        output = process.StandardOutput.ReadToEnd();
        // 如果重定向了错误输出,也可以读取:
        // string errorOutput = process.StandardError.ReadToEnd();
    }

    return output;
}

关键说明:

  • 超时判断:WaitForExit(1000)会阻塞当前线程,直到进程退出或1秒超时,返回值直接反映是否超时。
  • 终止超时进程:超时后必须调用Kill(),否则外部进程会继续运行,导致资源泄漏。
  • 输出读取顺序:将ReadToEnd()放在WaitForExit()之后,避免因外部程序输出缓冲区已满导致的进程挂起问题(如果先调用ReadToEnd(),进程可能因缓冲区无法写入而阻塞,无法触发超时判断)。
  • 可选优化:如果外部程序可能输出错误信息,建议开启RedirectStandardError = true并读取错误输出,方便排查问题;CreateNoWindow = true可以避免弹出外部程序的控制台窗口。

内容的提问来源于stack exchange,提问作者Usman Mehmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:22:07