C# process.StandardOutput.ReadLine() return 空

C# process.StandardOutput.ReadLine() return null

我有一个控制台应用程序并尝试在 C# Asp.Net Core 3.1 WebApi 应用程序中使用它。我使用的代码如下:

  1. 创建进程

    Process process;
    process = new Process();
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.FileName = executable;
    process.Start();
    
  2. 然后我继续使用下面的代码向控制台应用程序发送命令并读取输出

    process.StandardInput.WriteLine(argument);
    string output = string.Empty;
    do
    {
        Thread.Sleep(50);
        output = process.StandardOutput.ReadLine();
    } while (output == null);
    

结果是,对于前几个命令,我可以正确地从 ReadLine 函数中得到结果。然而,在几个命令之后,我一直得到 null 并且整个应用程序卡在 while 循环中。

我在控制台中 运行 控制台应用程序并一个接一个地发送输入第二步的命令,所有这些都可以 return 更正结果并按预期在控制台中打印结果。

任何人都可以帮助解决问题吗?谢谢

我刚刚用你的方法创建了解决方案,一切正常。我建议您使用 await Task.Delay(50) 而不是 Thread.Sleep(50) 所以有两个这样的控制台应用程序。首先是我要调用的应用程序(我称它为 "External" 一个:

static void Main(string[] args)
{
    string key = String.Empty;
    do
    {
        key = Console.ReadLine();
        Console.WriteLine($"{key} was pressed in external program");
    } while (key != "q");
}

以及调用此方法的应用程序:

        static async Task Main(string[] args)
        {
            using (Process process = new Process())
            {
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.FileName = @"[path_to_the_previous_console_app]\TestConsoleAppExternal.exe";
                process.Start();
                Console.WriteLine("Write some key");
                string key = String.Empty;
                do
                {
                    key = Console.ReadLine();
                    await Interact(process, key);
                } while (key != "q");
            }
        }

        static async Task Interact(Process process, string argument)
        {
            process.StandardInput.WriteLine(argument);
            string output = string.Empty;
            do
            {
                await Task.Delay(50);
                output = process.StandardOutput.ReadLine();
            } while (output == null);
            Console.WriteLine($"{argument} was pressed from Main process and readed output was: '{output}' ");
        }

一切都按设计运行。你到底想实现什么场景?你打电话给什么样的应用程序?也许这就是区别?