title: What is the proper way to programmatically close a WinForms application after a certain time?
body: <p>I start my form in the usual way:</p>
  
  <pre><code>Application.Run(new MainForm());
  </code></pre>
  
  <p>I want it to open and run until a certain time, then close.  I've tried the following but to no avail:</p>
  
  <p>(1) In the Main method (were the Application.Run() statement is), I enter the following AFTER Application.Run()</p>
  
  <pre><code>while (DateTime.Now &lt; Configs.EndService) { }
  </code></pre>
  
  <p>RESULT:  It never gets hit.</p>
  
  <p>(2) BEFORE Application.Run() I start a new Background Thread:</p>
  
  <pre><code>        var thread = new Thread(() =&gt; EndServiceThread()) { IsBackground = true };
          thread.Start();
  </code></pre>
  
  <p>where EndServiceThread is:</p>
  
  <pre><code>    public static void EndServiceThread()
      {
          while (DateTime.Now &lt; Configs.EndService) { }
          Environment.Exit(0);
      }
  </code></pre>
  
  <p>RESULT:  vshost32.exe has stopped working crash.</p>
  
  <p>(3) In MainForm Tick Event:</p>
  
  <pre><code>        if (DateTime.Now &gt; Configs.EndService)
          {
              this.Close();
              //Environment.Exit(0);
          }
  </code></pre>
  
  <p>RESULT:  vshost32.exe has stopped working crash.</p>
  
  <p>What is the proper way to achieve my goal?  Again, I want to launch the Form, have it open &amp; running until a certain time (Configs.EndService), then close.</p>
  
  <p>Thank you,
  Ben.</p>