【发布时间】:2014-05-05 11:41:47
【问题描述】:
我正在生产服务器上运行 Windows 服务。如果服务因任何原因崩溃,我们立即恢复是非常重要的,所以我写了一个监控服务,它的唯一目的是不断检查主服务是否启动并运行,如果没有,则发送求救信号。它还应该启动已关闭的服务......这是不工作的部分:
public static void CheckService(string checkServiceName, string myServiceName, bool restartIfStopped = false)
{
var ctl = ServiceController.GetServices()
.FirstOrDefault(s => s.ServiceName == checkServiceName);
var error = "";
if (ctl == null)
error = "{0} is not installed!".Fmt(checkServiceName);
else if (ctl.Status != ServiceControllerStatus.Running)
{
error = "{0} is in status {1}".Fmt(checkServiceName, ctl.Status);
if (restartIfStopped)
try
{
ctl.Start();
// no error = success
error += "\r\nService was automatically restarted.";
}
catch (Exception ex)
{
// send to windows application log
Log("Failed to restart service:\r\n"+ex, myServiceName, EventLogEntryType.Warning);
}
}
// other code here to send out email notifications
}
问题是当我尝试使用ctl.Start() 重新启动服务时,它会在应用程序日志中出现以下错误:
重启服务失败:
System.InvalidOperationException:无法在计算机“.”上打开 MyService 服务。 ---> System.ComponentModel.Win32Exception: 访问被拒绝
这两个服务都设置为使用“网络服务”运行。我已授予两个可执行文件夹上“网络服务”的完全安全权限。
还有什么可能导致这种情况?
【问题讨论】:
-
如果我没记错的话,你可以设置服务在失败时自动重启?
-
@GabrielNegut 你是对的!见here。你想把它作为答案,为了信用?
-
我很高兴它有帮助。我将其添加为答案(使用您提供的链接)。
标签: c# windows-services