简体   繁体   中英

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. 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.

Thanks in advance!!

On the machine where the service is running, you can open up the Services management console (start > run > 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.

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.

Well I'm assuming that you are creating a Windows Service project for what you are doing. Go into your ProjectInstaller and find the "AfterInstall" method. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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