如何使用c#控制台同时进行输入和日志记录

How to use C# console for input and logging at the same time

本文关键字:输入 日志 记录 何使用 控制台      更新时间:2023-09-26

我有一个c#控制台应用程序。我正在启动另一个cmd进程来使用我的NodeJS应用程序(也许有任何关于如何做到这一点的建议?我必须同时运行两个,它们是一起工作的。

现在NodeJS处理它的输出流到我的c#控制台。

private readonly Process _nodeProcess = new Process
{
    StartInfo =
    {
        FileName = "cmd",
        Arguments = @"/K Node server.js",
        UseShellExecute = false,
        RedirectStandardOutput = true
    }
};
internal void Start()
{
    _nodeProcess.Start();
    using (StreamReader reader = _nodeProcess.StandardOutput)
    {
        while (true)
        {
            string result = reader.ReadLine();
            Console.WriteLine(result);
        }
    }
}

这很好。现在的问题是,我的Node记录了一些东西,但同时我希望能够在我的控制台上给出命令(输入)。

我的控制台输出示例:(当然它使用了整个系统,输出真实的东西…)

NodeJS process started
node log 1
node log 2
node log ...

等等…

但是,当它继续输出我的日志行时,我希望能够使用Console.ReadLine();输入(用于命令输入)。这样就不会有在与输出行相同的行中输入的风险。

我将感激任何帮助。任何改进我的代码的建议都是欢迎的。

在您的情况下,最好异步处理输出

首先在输出中添加一个eventandler:

_nodeProcess.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);

然后在_nodeProcess.Start();

后面加上_nodeProcess.BeginOutputReadLine();

类似:

 _nodeProcess.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
 _nodeProcess.Start();
 _nodeProcess.BeginOutputReadLine();
 var line = Console.ReadLine();
 while (line != null && line.ToLower() != "exit")
 {
      line = Console.ReadLine();
 }
 _nodeProcess.Close();