Cannot restart a Service

后端 未结 1 1898
萌比男神i
萌比男神i 2020-12-22 10:44

I have this code to restart a service, but this is not working.

I can start and stop individually but not restart which involves me to first stop and start the servi

1条回答
  •  一整个雨季
    2020-12-22 11:33

    Having an empty catch block catching all exceptions is rarely a good idea as serious problems easily slip through.

    Modify your code to at least do some logging in the catch block, e.g.

    catch (Exception ex)
    {
        System.Diagnostics.Trace.WriteLine(ex.ToString());
    }
    

    You can then either attach a trace listener in the constructor of your service or use the DebugView tool from Sysinternals to read the trace message. If you want to take this a step further you might want to include a logging library like log4net into your project.

    My guess would be that your are getting a TimeoutException because stopping the service takes longer as you expected. Have you tried increasing the timeout or waiting infinitely by removing the timeout parameter?

    Update:

    You probably need to check whether your service is started or not:

    if  (!(service.Status.Equals(ServiceControllerStatus.Stopped) 
           || service.Status.Equals(ServiceControllerStatus.StopPending)))
    {
        service.Stop();
    }
    service.Start();
    

    0 讨论(0)
提交回复
热议问题