[英]How to use C# console for input and logging at the same time
I have got a C# console application. 我有一个C#控制台应用程序。 I'm starting up another cmd process to use my NodeJS app (maybe any advise on how to do this otherwise? I have to run both at the same time, they work togheter). 我正在启动另一个cmd进程以使用我的NodeJS应用程序(也许对如何执行此操作有任何建议吗?我必须同时运行这两个程序,它们才能正常工作)。
Now the NodeJS process its output is streamed to my C# console. 现在,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);
}
}
}
This works fine. 这很好。 Now the problem here is, my Node logs something, but meanwhile I want to be able to give commands (input) on my console. 现在的问题是,我的Node记录了一些内容,但是与此同时,我希望能够在控制台上提供命令(输入)。
Example of my console output: (of course it uses a whole system, outputting real stuff..) 我的控制台输出示例:(当然,它使用整个系统,输出实际内容。)
NodeJS process started
node log 1
node log 2
node log ...
and so on .. 等等 ..
But while it keeps outputting my log lines, I want to be able to type (for command input) with Console.ReadLine();
但是尽管它一直输出我的日志行,但我希望能够使用Console.ReadLine();
键入(用于命令输入Console.ReadLine();
. 。 This without the risk of typing inside the same line as an output line. 这样就没有在输出行中键入同一行的风险。
I would appreciate any help. 我将不胜感激任何帮助。 Any suggestions on improving my code are welcome. 欢迎提出改进我的代码的任何建议。
In your case it would be better to handle the output Asynchronously . 在您的情况下,最好异步处理输出。
First add an Eventhandler to your Output: 首先向您的输出添加一个事件处理程序:
_nodeProcess.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
Then add the line _nodeProcess.BeginOutputReadLine();
然后添加_nodeProcess.BeginOutputReadLine();
行_nodeProcess.BeginOutputReadLine();
after _nodeProcess.Start();
_nodeProcess.Start();
Something like: 就像是:
_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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.