首页 > 解决方案 > Topshelf 如何处理未处理的异常?

问题描述

我知道有一个事件 OnException 来记录未处理的异常,但它无法停止 Topshelf 服务。结果,在发生未处理的异常时,topshelf 服务停止。

预期:如果出现未处理的异常,topshelf 会记录它而不停止或退出 topshelf 服务。

请帮忙?

 var rc = HostFactory.Run(x =>                                   //1
            {
                x.Service<TestService>(s =>
                {                    
                    s.ConstructUsing(name => new TestService());
                    s.WhenStarted((tc,hc) => tc.Start(hc));
                    s.WhenStopped((tc,hc) => tc.Stop(hc));     
                });

                x.SetInstanceName("TestService11");

                x.SetDescription("Test Service");                   //7
                x.SetDisplayName("TestService 11");                                  //8
                x.SetServiceName("TestService11");
                x.RunAs(".\administrator", "passwor123");

                x.StartAutomatically(); 

                x.UseLog4Net();

                x.UnhandledExceptionPolicy = UnhandledExceptionPolicyCode.LogErrorOnly;                

                x.EnableServiceRecovery(r =>
                {
                    // Has no corresponding setting in the Recovery dialogue.
                    // OnCrashOnly means the service will not restart if the application returns
                    // a non-zero exit code.  By convention, an exit code of zero means ‘success’.
                    r.OnCrashOnly();
                    // Corresponds to ‘First failure: Restart the Service’
                    // Note: 0 minutes delay means restart immediately
                    r.RestartService(0);
                    // Corresponds to ‘Second failure: Restart the Service’
                    // Note: TopShelf will configure a 1 minute delay before this restart, but the
                    // Recovery dialogue only shows the first restart delay (0 minutes)
                    r.RestartService(1);
                    // Corresponds to ‘Subsequent failures: Restart the Service’
                    r.RestartService(2);
                    // Corresponds to ‘Reset fail count after: 1 days’
                    r.SetResetPeriod(1);
                });

                x.OnException((ex) =>
                {
                    HostLogger.Get<TestService>().Info("Exception occured Main : " + ex.ToString());
                });


            });

标签: c#unhandled-exceptiontopshelf

解决方案


推荐阅读