简体   繁体   中英

Unable to catch ServiceController.Start() exceptions in calling thread

How can i catch the exception that occurs when starting a windows service. I am unable to get the exception here in my below code even though i am throwing exception in the Onstart() method of the service.

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

Calling thread code

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;
}

i check for application license in the onstart() method and throws a licensing error if it fails. i want this to shared to my calling thread so i could show the message in a DialogBox. Any ideas of how to do this if i cannot handle the exceptions in my calling process.

Separate your service into (at least) two components - a component that deals with IPC in some form (eg Remoting, WCF endpoint, REST service, etc) and (one or more) components that do its actual job.

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.

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