C#类过程 - 控制C 应用程序,不可能读取输出

C# Class Process - Control C++ application, impossibility Read Output

本文关键字:不可能 读取 输出 应用程序 过程 控制      更新时间:2023-10-16

我需要控制C#应用中C 编写的控制台应用程序。C#应用程序无法从C 应用程序的输出中读取任何内容。使用函数process.StandardOutput.ReadLine()时,应用程序会冻结。我尝试在C#,C 中创建简单的控制台应用,仅使用PRINTF(" Test Shamp r n"(和Console.Writeline("测试示例"(。示例C#应用程序效果很好,C 不可能。所以我不知道我在哪里犯错。可能C 应用程序写了不良的线路,但我不知道该如何解决。

C#中的主应用程序的代码示例,该代码控制了用C 或C#写的另一个应用程序。

            process= new Process()
            {
                StartInfo = new ProcessStartInfo(@"testApp")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                }
            };
            process.Start();                
            inputWriter = process.StandardInput;                
            string text =process.StandardOutput.ReadLine();//C++ app freezes here    

和两个测试应用

在C

int main(){
while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    printf("Test send datarn");               
}
return 0;}

在C#

static void Main(string[] args)
    {
        while (true)
        {
            Thread.Sleep(500);
            Console.WriteLine("Test send data");
        }
    }

看一下以下答案:processstartinfo挂在" waitforeforexit"上。为什么?和standardOutput.readline((使用C#挂起应用程序 他们都可以提供解释和解决方案。

我也尝试使用ReadLineAsync:

while ((line = await process.StandardOutput.ReadLineAsync()) != null)
    Console.WriteLine(line);

它起作用。请注意,如果选择了此解决方案,则必须对代码进行一些更改以使其async(您也可以将其包装在任务中,这完全取决于您的需求(。