0

如何捕获启动 Windows 服务时发生的异常。即使我在服务的 Onstart() 方法中抛出异常,我也无法在下面的代码中获取异常。

public class InterOpIntegrationWinService : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        throw new InvalidOperationException(message);
    } 
}

调用线程代码

try
{
    using (ServiceController controller = new ServiceController())
    {
        controller.ServiceName = objServiceConfig.ServiceName;
        controller.Start();
        System.Windows.Forms.Application.DoEvents();
        //controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 15));
        //controller.WaitForStatus(ServiceControllerStatus.Running);
        //if (!string.IsNullOrEmpty(LogUtilities.ServiceOnStartException))
        //{
        //    MessageBox.Show("Error with starting service : " + LogUtilities.ServiceOnStartException);
        //    LogUtilities.ServiceOnStartException = string.Empty;
        //}
    }
}
catch (System.InvalidOperationException InvOpExcep)
{
    DisplayError(InvOpExcep.Message);
    LogUtilities.DisplayMessage("Failed to start service. " + LogUtilities.ServiceOnStartException, InvOpExcep);
    LogUtilities.ServiceOnStartException = string.Empty;
}
catch (Exception ex)
{
    DisplayError(ex.Message);
    LogUtilities.DisplayMessage("Failed to start service. " + LogUtilities.ServiceOnStartException, ex);
    LogUtilities.ServiceOnStartException = string.Empty;
}

我在 onstart() 方法中检查应用程序许可证,如果失败则抛出许可错误。我希望将此共享给我的调用线程,以便我可以在对话框中显示消息。如果我无法处理调用过程中的异常,有关如何执行此操作的任何想法。

4

1 回答 1

2

将您的服务分成(至少)两个组件——一个以某种形式处理IPC的组件(例如 Remoting、WCF 端点、REST 服务等)和(一个或多个)执行其实际工作的组件。

If the licensing check fails, don't start the other components - but do still start the component that offers IPC. After starting your service (which should now always at least start), you forms-based application can connect to the service and (through whatever means you want) determine that the service is currently refusing to provide any functionality due to a failed licensing check.

于 2015-09-11T11:00:56.693 回答