Process StandardOutput ReadToEnd在多个进程时获取null/空字符串

本文关键字:null 获取 字符串 进程 ReadToEnd StandardOutput Process | 更新日期: 2023-09-27 18:10:07

我尝试使用Parallel.For来运行进程并并行获得输出。

示例代码如下:
internal class Program
{
    private static void Main(string[] args)
    {
        var bag = new ConcurrentBag<string>();
        Parallel.For(0, int.MaxValue, i =>
        {
            bag.Add(MyMethod());
        });
    }
    public static string MyMethod()
    {
        using (var a = new Process())
        {
            a.StartInfo.FileName = "A.exe";
            a.StartInfo.RedirectStandardError = true;
            a.StartInfo.RedirectStandardInput = true;
            a.StartInfo.RedirectStandardOutput = true;
            a.StartInfo.CreateNoWindow = true;
            a.StartInfo.UseShellExecute = false;
            a.StartInfo.ErrorDialog = false;
            a.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            a.Start();
            string output = a.StandardOutput.ReadToEnd();
            a.WaitForExit();
            return output; // sometime output will be null
        }
    }
}

A.exe代码

internal class Program
{
    private static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 40; j++)
            {
                Console.Write("A");
            }
            Console.Write(Environment.NewLine);
        }
    }
}

有人知道为什么输出将为空,我如何避免得到空结果?

Process StandardOutput ReadToEnd在多个进程时获取null/空字符串

我试着弄清楚为什么在流中得到null。

如果我在A.exe输出前添加Thread.Sleep(),主进程的ReadToEnd()将等待A.exe输出并获得结果。

只有一种情况会导致空流,即A.exe退出且没有输出。

这将让ReadToEnd()得到null和Peek()没有帮助,因为A.exe退出,不再输出了。

我认为我的问题是我的程序运行在一个沉重的负载Windows Server 2003 R2 32位,Process.Start()没有得到异常时,进程无法启动。它导致流没有输出,进程退出,流关闭。