我有一个控制台应用程序,并试图在C# Asp.Net Core 3.1 WebApi应用程序中使用它。我使用的代码如下。
创建进程
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();
然后,我一直使用下面的代码向控制台应用程序发送命令,并读取输出。
process.StandardInput.WriteLine(argument);
string output = string.Empty;
do
{
Thread.Sleep(50);
output = process.StandardOutput.ReadLine();
} while (output == null);
结果是,在最初的几个命令中,我可以从ReadLine函数中得到正确的结果。然而,在几条命令之后,我一直得到null,整个应用程序卡在while循环。
我在控制台中运行了控制台应用程序,并逐个发送命令进入第二步,所有这些命令都能返回正确的结果,并按照预期在控制台中打印结果。
谁能帮帮我,可能是什么问题?谢谢你的帮助
我刚刚用你的方法创建了解决方案,一切都在正常工作。我建议你使用 await Task.Delay(50)
比 Thread.Sleep(50)
所以有两个这样的控制台应用程序。首先是我想调用的应用程序(我称它为 "外部 "应用程序。
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}' ");
}
一切都按设计的方式运行。你到底想实现什么场景?你调用的是什么样的应用程序?也许这就是区别?