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

时间:2016-05-12 17:36:05

标签: c# node.js process exit

我正在将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 方法。我不知道为什么,我看不到任何模式。大多数时候都不会停止。

1 个答案:

答案 0 :(得分:1)

您正在使用WaitForExit(),因此没有理由使用Exited事件。

只需在WaitForExit()之后手动调用您的处理程序,如下所示:

_nodeProcess.WaitForExit();    
_nodeProcess.Close();
nodeExited(_nodeProcess, new EventArgs());

并删除

_nodeProcess.EnableRaisingEvents = true;
_nodeProcess.Exited += nodeExited;

编辑:

如果我理解this正确答案,您可能也会遇到死锁,因为您拨打了StandardError.ReadToEnd();然后StandardOutput.ReadToEnd();。 StandardOutput缓冲区在达到该点之前可能已满。

相关问题