即使在进程退出后,Proc.WaitforExit()调用是否也会阻塞线程

时间:2018-07-11 08:58:30

标签: c# asynchronous process stream

我正在启动一个进程并异步读取标准输出和错误流,下面是这样做的代码。该api是否有可能阻塞线程或问题出在我代码的其他地方< / strong>,因为该线程仅在此api调用之前打印调试语句,但在此api调用之后不打印任何调试日志。因此,我怀疑该线程正在阻塞该线程或以其他方式杀死了该线程,因此不打印任何内容

请在这里帮助我

  public static string start_proc(string proc_name, string param, int timeout = 8000)
    {
        string Proc_Data = string.Empty;
        bool Hasexited = false;
        StringBuilder outputdata = new StringBuilder("");
        StringBuilder errordata = new StringBuilder("");
        Process Proc = new Process();
        ProcessStartInfo ProcStartInfo = new ProcessStartInfo(proc_name, param);
        ProcStartInfo.UseShellExecute = false;
        ProcStartInfo.RedirectStandardOutput = true;
        ProcStartInfo.RedirectStandardError = true;
        ProcStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        ProcStartInfo.CreateNoWindow = true;
        Proc.StartInfo = ProcStartInfo;
        Proc.OutputDataReceived += new DataReceivedEventHandler((object sender, DataReceivedEventArgs args) => OutputHandler(outputdata, sender, args));
        Proc.ErrorDataReceived += new DataReceivedEventHandler((object sender, DataReceivedEventArgs args) => OutputHandler(errordata, sender, args));

        try
        {
            Proc.Start();
            Proc.BeginOutputReadLine();
            Proc.BeginErrorReadLine();
            Hasexited = Proc.WaitForExit(timeout);
            if (Hasexited)
                Proc.WaitForExit();
            Proc_Data = outputdata.Append(errordata).ToString();
            Proc.Close();
        }
        catch (Exception ex)
        {
            TraceText(TRACEID, "E", " : " + ex.ToString());
        }
        return Proc_Data;
    }

    private static void OutputHandler(StringBuilder data, object sendingProcess,
        DataReceivedEventArgs outLine)
    {

        if (!String.IsNullOrEmpty(outLine.Data))
        {
            data.Append(outLine.Data + Environment.NewLine);

        }
    }

0 个答案:

没有答案