在 C# 中将 nodejs 作为进程重新启动
Restarting nodejs as a process in C#
我将 NodeJs 作为 C# 应用程序中的进程启动。我的意图是在每次停止时重新启动该过程。
启动进程的代码是:
_nodeProcess = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = location,
FileName = "node.exe",
Arguments = "main.js"
}
};
_nodeProcess.EnableRaisingEvents = true;
_nodeProcess.Exited += nodeExited;
_nodeProcess.Start();
string stderrStr = _nodeProcess.StandardError.ReadToEnd();
string stdoutStr = _nodeProcess.StandardOutput.ReadToEnd();
if (!String.IsNullOrWhiteSpace(stderrStr))
{
LogInfoMessage(stderrStr);
}
LogInfoMessage(stdoutStr);
_nodeProcess.WaitForExit();
_nodeProcess.Close();
这里是 nodeExited 方法:
private void nodeExited(object sender, EventArgs e)
{
if (!_isNodeStop)
{
this.restartERM_Click(sender, e);
}
else
{
_isNodeStop = false;
}
}
_isNodeStop 只是我在从受控位置杀死节点时设置为 true 的标志。
像这样:
private void KillNode()
{
foreach (var process in Process.GetProcessesByName("node"))
{
_isNodeStop = true;
process.Kill();
}
}
我的问题是 nodeExited 方法不会在每次节点停止时触发。我不知道为什么,也看不到任何模式。大多数时候只是不停下来。
无论如何您都在使用 WaitForExit(),因此没有理由使用 Exited 事件。
只需在 WaitForExit() 之后手动调用您的处理程序,如下所示:
_nodeProcess.WaitForExit();
_nodeProcess.Close();
nodeExited(_nodeProcess, new EventArgs());
并移除
_nodeProcess.EnableRaisingEvents = true;
_nodeProcess.Exited += nodeExited;
编辑:
如果我理解 this 回答正确,您可能还会遇到死锁,因为您调用了 StandardError.ReadToEnd();
,然后又调用了 StandardOutput.ReadToEnd();
。 StandardOutput 缓冲区甚至可能在达到该点之前就已满。
我将 NodeJs 作为 C# 应用程序中的进程启动。我的意图是在每次停止时重新启动该过程。
启动进程的代码是:
_nodeProcess = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = location,
FileName = "node.exe",
Arguments = "main.js"
}
};
_nodeProcess.EnableRaisingEvents = true;
_nodeProcess.Exited += nodeExited;
_nodeProcess.Start();
string stderrStr = _nodeProcess.StandardError.ReadToEnd();
string stdoutStr = _nodeProcess.StandardOutput.ReadToEnd();
if (!String.IsNullOrWhiteSpace(stderrStr))
{
LogInfoMessage(stderrStr);
}
LogInfoMessage(stdoutStr);
_nodeProcess.WaitForExit();
_nodeProcess.Close();
这里是 nodeExited 方法:
private void nodeExited(object sender, EventArgs e)
{
if (!_isNodeStop)
{
this.restartERM_Click(sender, e);
}
else
{
_isNodeStop = false;
}
}
_isNodeStop 只是我在从受控位置杀死节点时设置为 true 的标志。
像这样:
private void KillNode()
{
foreach (var process in Process.GetProcessesByName("node"))
{
_isNodeStop = true;
process.Kill();
}
}
我的问题是 nodeExited 方法不会在每次节点停止时触发。我不知道为什么,也看不到任何模式。大多数时候只是不停下来。
无论如何您都在使用 WaitForExit(),因此没有理由使用 Exited 事件。
只需在 WaitForExit() 之后手动调用您的处理程序,如下所示:
_nodeProcess.WaitForExit();
_nodeProcess.Close();
nodeExited(_nodeProcess, new EventArgs());
并移除
_nodeProcess.EnableRaisingEvents = true;
_nodeProcess.Exited += nodeExited;
编辑:
如果我理解 this 回答正确,您可能还会遇到死锁,因为您调用了 StandardError.ReadToEnd();
,然后又调用了 StandardOutput.ReadToEnd();
。 StandardOutput 缓冲区甚至可能在达到该点之前就已满。