title: windows service will not stop when I select stop from the services windows C#
body: <p>I have written a windows service but when I try to stop the service it says that the service cannot be stopped at this time. Here's my whole class:</p>
  
  <pre><code>public partial class RenewalsService : ServiceBase
  {
      private readonly ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
      private Thread _thread;
  
      public RenewalsService()
      {
          InitializeComponent();
          this.CanStop = true; 
      }
  
      protected override void OnStart(string[] args)
      {
          _thread = new Thread(WorkerThread)
          {
              Name = "Renewals Service Thread",
              IsBackground = true
          };
          _thread.Start();
      }
  
      protected override void OnStop()
      {
          try
          {
  
              if (!_shutdownEvent.SafeWaitHandle.IsClosed)
              {
                  _shutdownEvent.Set();
              }
              if (_thread.IsAlive)
              {
                  if (!_thread.Join(3000))
                  {
                      // give the thread 3 seconds to stop
                      _thread.Abort();
                  }
              }
          }
          catch (Exception ex)
          {
              // _thread.Join may raise an error at this point. If it does we dont care. We dont care about any other exceptions
              // since we are already in the process of closing the service.
  
          }
          finally
          {
              IError logger = new Logger();
              Exception ex = new Exception("The Renewals service has been stopped.");
              logger.Log(this, SeverityEnum.Warning, ex);
              Environment.ExitCode = 0;
              Environment.Exit(Environment.ExitCode);
          }
      }
  
  
      private void WorkerThread()
      {
          try
          {
              while (!_shutdownEvent.WaitOne(1))
              {
  
                  string timeToRun = ConfigurationManager.AppSettings["RunTime"];
                  string[] timeStrings = timeToRun.Split(':');
                  TimeSpan runtime = new TimeSpan(0, Int32.Parse(timeStrings[0]), Int32.Parse(timeStrings[1]), Int32.Parse(timeStrings[2]));
  
                  if (DateTime.Today.TimeOfDay.Hours == runtime.Hours &amp;&amp;
                      DateTime.Today.TimeOfDay.Minutes == runtime.Minutes)
                  {
                      Renewals renewals = new Renewals();
                      renewals.GenerateRenewal();
  
                  }
              }
          }
          catch (Exception ex)
          {
              IError logger = new Logger();
              logger.Log(this, SeverityEnum.Warning, ex);
              this.OnStop();
  
          }
  
      }
  }
  </code></pre>
  
  <p>What's missing to ensure the user can stop the service.</p>