title: Dispose a form in ApplicationContext before calling Application.Restart
body: <p>I have a winforms application that uses a custom application context which provides the framework to run the application in the system tray.</p>
  
  <pre><code>public partial class MyApplicationContext : ApplicationContext
  {
      private IContainer components;
      private NotifyIcon notifyIcon = null;
  
      /// the main application form, which may never be shown
      private AppForm appForm = null;
  
      public MyApplicationContext() 
      {
          components = new System.ComponentModel.Container();
          notifyIcon = new NotifyIcon(components)
          {
              ContextMenuStrip = new ContextMenuStrip(),
              Icon = Properties.Resources.icon2a,
              Text = "Application",
              Visible = true
          };
  
          appForm = new AppForm();
      }
  }
  </code></pre>
  
  <p>The application watches for changes to a config file, and restarts itself as necessary.</p>
  
  <pre><code>private void requestRestart()
  {
      /// dispose the application context
      this.Dispose(); 
      Application.Restart();
  }
  </code></pre>
  
  <p>I have to dispose the application context before restarting as there are resources which will be required by the new instance of the application. However <code>requestRestart()</code> may be called from <strong>another thread.</strong> So I can't dispose of <code>appForm</code> in the <code>ApplicationContext.Dispose()</code> method or directly in the restart method, or I will get a cross-threading exception.</p>
  
  <p>If the form has been shown before the restart when the user clicks on the tray icon which calls <code>appForm.Show()</code> then <code>appForm.Dispose(true)</code> will be called automatically.  Per <a href="https://msdn.microsoft.com/en-us/library/aw58wzka%28v=vs.100%29.aspx" rel="nofollow">MSDN</a>:</p>
  
  <blockquote>
    <p>Dispose will be called automatically if the form is shown using the Show method. </p>
  </blockquote>
  
  <p>Otherwise, if the form is never shown, the GC finalizer calls <code>Dispose(false)</code>.</p>
  
  <p>How can I make sure this form is disposed before the restart?</p>