简体   繁体   English

崩溃时自动重启自托管的WCF服务

[英]Automatically restart a self hosted wcf service on crash

I have a self hosted wcf service that is using legacy c++ code via dll import and pinvoke. 我有一个自托管的wcf服务,该服务通过dll导入和pinvoke使用旧版c ++代码。 There are some instances in the old code where exceptions arise from the functions (that were handled in the old app, but not in the service) and when they occur my service is stopping. 在旧代码中有一些实例,这些异常来自功能(在旧应用程序中处理,但不在服务中处理),当它们发生时,我的服务就停止了。 The exceptions are rare; 例外情况很少见; however, I do not want my service just randomly stopping as a result of a crash in another assembly. 但是,我不希望我的服务只是由于另一个程序集的崩溃而随机停止。 The exceptions are not bubbling up to the service so I cannot try/catch them in the service. 异常不会影响服务,因此我无法在服务中尝试/捕获它们。 Is there a way to automatically have the service restart on crash? 有没有一种方法可以使服务自动崩溃?

It is self hosted, not through IIS. 它是自托管的,而不是通过IIS。

Thanks in advance!! 提前致谢!!

On the machine where the service is running, you can open up the Services management console (start > run > services.msc). 在运行服务的计算机上,可以打开服务管理控制台(开始>运行> services.msc)。 Find your service, right-click it and choose Properties. 找到您的服务,右键单击它,然后选择“属性”。 In the popup, click on the Recovery tab. 在弹出窗口中,单击“恢复”选项卡。 Set First, Second, and Subsequent failures all to Restart the Service. 将“第一,第二和后续故障”设置为全部以重新启动服务。

If you are using WIX to install your project, you can also set these properties using the util:ServiceConfig element. 如果使用WIX安装项目,则还可以使用util:ServiceConfig元素设置这些属性。

If you're using a standard ServiceInstaller, these options aren't built in. I'd recommend having a look at the ServiceInstaller Extension class which exposes properties through a standard service installer interface. 如果您使用的是标准ServiceInstaller,则不会内置这些选项。建议您查看一下ServiceInstaller Extension类,该类通过标准服务安装程序界面公开属性。

Well I'm assuming that you are creating a Windows Service project for what you are doing. 好吧,我假设您正在为自己的工作创建Windows Service项目。 Go into your ProjectInstaller and find the "AfterInstall" method. 进入您的ProjectInstaller并找到“ AfterInstall”方法。 Here you will need to add code to execute a command on the Service Controller to set recovery options. 在这里,您将需要添加代码以在服务控制器上执行命令以设置恢复选项。 Unfortunatly, even though .NET has a ServiceController you will need to execute the command through a process start. 不幸的是,即使.NET具有ServiceController,您仍需要通过进程启动来执行命令。

using (var process = new Process())
{
    var startInfo = process.StartInfo;
    startInfo.FileName = "sc";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;

    // tell Windows that the service should restart if it fails
    startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);

    process.Start();
    process.WaitForExit();

    exitCode = process.ExitCode;

    process.Close();
}

Note: I stole this code from another question 注意:我从另一个问题中 窃取了此代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM