title: How do I quit a Windows service from inside the service?
body: <p>I have a Windows Service.  On startup it checks whether any work has been assigned to it - and if none has, it just quits.  The problem is that the recovery mechanism is set to Restart the Service.  </p>
  
  <p><a href="https://i.stack.imgur.com/dhuj8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dhuj8.png" alt="enter image description here"></a></p>
  
  <p>This is what I want if the service legitimately crashes, but not if I quit the service programmatically on my own. </p>
  
  <p>So far everything I've tried below has resulted in Windows automatically restarting the service:</p>
  
  <pre><code>Thread th;
  protected override void OnStart(string[] args)
  {
      th = new Thread(new ThreadStart(StartMyService));
      th.Start();
  }
  
  private void StartMyService()
  {
      if (WorkAvailable()) {
        InitWork();
      } else {
        this.ExitCode = 0;  // no errors
        Stop();
      }
  }
  
  protected override void OnStop()
  {
      // dispose of things
  
      try
      {
          if (th != null &amp;&amp; th.ThreadState == ThreadState.Running)
              th.Abort();
      }
      catch { }
  
      Environment.Exit(this.ExitCode);
  }
  </code></pre>
  
  <p>I've tried different ExitCode values, but Windows always restarts the Service.  I've also tried <code>Environment.FailFast</code> with same results. What am I missing?    </p>