Stop service without error "Service cannot be started. The handle is invalid"

16,512

Use a thread to make sure the OnStart method finishes. The threadpool will put your workitem on the queue and once a thread it is available it will execute your Run method and then calls Stop on the service. By then the windows service manager already handled the succesful start of your service and hence no error will be sent to the Eventlog when Stop is called.

    protected override void OnStart(string[] args)
    {            
        EventLogger.Write("Starting service!");
        ThreadPool.QueueUserWorkItem( _ => {
            new VirtualServerInit(EventLogger).Run();
            EventLogger.Write("VirtualServerInit code was executed");            
            this.Stop();
         });
     }

You might consider leaving the service running and use a CustomCommand to control if actual work needs to be done. For that you can override OnCustomCommand and send a pre determined integer to ask the service to perform a particular task for example by calling sc virtualsvc control 128 from the commandline.

protected virtual void OnCustomCommand(int command)
{
    switch(command)
    {
        case 128:
            new VirtualServerInit(EventLogger).Run();
            EventLogger.Write("VirtualServerInit code was executed");            
            // maybe keep state if this only can be run once
            break;
        default:
           EventLogger.Write(String.Format("Unknown control code:{0}", command));            
           break;
    }
}
Share:
16,512
Tomas
Author by

Tomas

Updated on June 04, 2022

Comments

  • Tomas
    Tomas almost 2 years

    I have WIndows Service app and want to stop service when main code is executed. I am trying to execute ServiceBase.Stop() in OnStart event, everything works fine, the service is stopped but I get annoying error message in event viewer

    "Service cannot be started. The handle is invalid" 
    

    Any ideas how to stop windows service without errors?

     public partial class VirtualServerInitService : ServiceBase
        {
    
            public ILogger EventLogger = new EventLogger();
    
            public VirtualServerInitService()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {            
                EventLogger.Write("Starting service!");
                new VirtualServerInit(EventLogger).Run();
                EventLogger.Write("VirtualServerInit code was executed");            
                Stop();//This code works and also gives error in event viewer
            }
    
            protected override void OnStop()
            {
                EventLogger.Write("Stopping service!");
            }
        }