[英]How to use C# console for input and logging at the same time
我有一個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();
鍵入(用於命令輸入Console.ReadLine();
。 這樣就沒有在輸出行中鍵入同一行的風險。
我將不勝感激任何幫助。 歡迎提出改進我的代碼的任何建議。
在您的情況下,最好異步處理輸出。
首先向您的輸出添加一個事件處理程序:
_nodeProcess.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
然后添加_nodeProcess.BeginOutputReadLine();
行_nodeProcess.BeginOutputReadLine();
_nodeProcess.Start();
就像是:
_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.