title: What is the right way to exit Windows Service OnStart if configuration is wrong and nothing to do?
body: <p>This is what I got:</p>
  
  <pre><code>protected override void OnStart(string[] args)
  {
      if (SomeApp.Initialize())
      {
          SomeApp.StartMonitorAndWork();
          base.OnStart(args);
      }
  }
  
  protected override void OnStop()
  {
      SomeApp.TearDown();
      base.OnStop();
  }
  </code></pre>
  
  <p>Here Initialize reads a config file and if it's wrong there's nothing to do so service should STOP! If config is ok StartMonitorAndWork starts:</p>
  
  <pre><code>Timer(new TimerCallback(DoWork), null, startTime, loopTime);
  </code></pre>
  
  <p>and DoWork polls database periodically. </p>
  
  <p>If Initialize fails (i check log file) and I try to stop service from Administrative Tools->Services i get:</p>
  
  <pre>
  Could not stop the SomeService on Local Computer. The service did not return an error. 
  This could be internal Windows error or an internal service error. 
  If the problem persists, contact system administrator.
  </pre>
  
  <pre>
  The question is: 
  "Is exiting OnStart without doing nothing enough if Initialize returns false?
  </pre>
  
  <p>OR should there be something like this:</p>
  
  <pre><code>private void ExitService()
  {
      this.OnStop();
      System.Environment.Exit(1);
  }
  
  protected override void OnStart(string[] args)
  {
      if (ObjectFolderApp.Initialize())
      {
          SomeApp.StartMonitorAndWork();
          base.OnStart(args);
      }
      else
      {
          ExitService();
      }
  }
  </code></pre>
  
  <p>Thanks &amp; BR - Matti</p>
  
  <p>EDIT:
  I came up with something like this:</p>
  
  <pre><code>protected override void OnStart(string[] args)
  {
      try
      {
          if (SomeApp.Initialize())
          {
              SomeApp.StartMonitorAndWork();
              base.OnStart(args);
          }
          else
          {
              Stop();
          }
      }
      catch
      {
          Stop();
      }
  }
  
  protected override void OnStop()
  {
      try
      {
          SomeApp.TearDown();
          base.OnStop();
      }
      catch
      {
          base.OnStop();
      }
  }
  </code></pre>