如何在我的 C# app-1 中实时读取 C# app-2 控制台应用程序的标准控制台输出?

问题描述 投票:0回答:1

目前,在我的 C# app-1 中,当控制台应用程序退出时,我可以读取一次 C# 控制台应用程序 (app-2) 的标准控制台输出。这很好用。

但在我的新用例中,控制台应用程序 (app-2) 将生成循环一些值(每 1 秒一次,总共 20 秒)。我想在生成这些值后立即从我的 app-1 中读取它们。这意味着在我的 app-1 中,我应该能够看到给定时间跨度的“实时”值变化。我所说的直播并不是指实时,有些延迟是可以接受的。

我当前的应用程序-1:

         public void Read_Std_Output_app2()
         {
            Process_app2 = new Process                
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = app2_path,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true
                }
            };
            Process_app2.Start();
            item_value = Process_app2.StandardOutput.ReadToEnd();
            Process_app2.WaitForExit();
         }

我当前的app-2:(生成输出一次)

        static void Main(string[] args)
        {
          // code for generating output
          Console.WriteLine(item_value_output)
          Environment.Exit(0);
        }

我的 app-2 具有循环价值生成功能:(新用例)

        static void Main(string[] args)
        {    
           while(var_true)
           {
             // code for generating cyclic output
             Console.Clear()
             Console.WriteLine(item_value_output)
             System.Threading.Thread.Sleep(1000)
           }
        }
c# console-application
1个回答
0
投票

您只需要更改代码中的一些内容即可。

 Process_app2 = new Process                
 {
     StartInfo = new ProcessStartInfo
     {
         FileName = app2_path,
         Arguments = arguments,
         UseShellExecute = false,
         RedirectStandardOutput = true,
         CreateNoWindow = true
     }
 };

//You need to capture the data in an event method 
Process_app2.OutputDataReceived += myOutputDataReceived;
Process_app2.Start();

//After starting the app, execute  this method to start to read the data as it is generated, then wait to exit.
Process_app2.BeginOutputReadLine();                
Process_app2.WaitForExit();

然后创建您的新方法

private void myOutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine($"{e.Data}");
}

您可能还需要从 App2 中删除

Console.Clear()
行,因为这可能会给您带来问题。

© www.soinside.com 2019 - 2024. All rights reserved.