在C#中将nodejs作为进程重新启动



我将NodeJ作为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;

编辑:

如果我正确理解这个答案,您可能也会出现死锁,因为您先调用StandardError.ReadToEnd();,然后调用StandardOutput.ReadToEnd();。StandardOutput缓冲区可能在达到该点之前就已满。

最新更新