title: What happens when a Dispatcher created on a background thread is not shutdown? How to make sure that a dispatcher is properly shut down?
body: <p>The following is one of the remarks on Dispatcher class.</p>
  
  <blockquote>
    <p>If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.</p>
  </blockquote>
  
  <p>What are the consequences if one fails to invoke shut down on a dispatcher created on a background thread?</p>
  
  <p>I have an MFC application which creates a WPF window on a background thread.  Consequently, a dispatcher is created.  When I close the WPF window first, I get to explicitly invoke shutdown on the dispatcher, but when I close the MFC application, the WPF window closes along.</p>
  
  <p>It seems the dispatcher is being shut down implicitly, or the thread is being aborted.  Which is it?</p>
  
  <p>Update:</p>
  
  <p>The following method creates a new thread and opens the wpf window.</p>
  
  <pre><code>public void ShowWindow(SomeObject someObject)
  {
      System.Threading.Thread thread = new System.Threading.Thread((tuple) =&gt;
          {
              Tuple&lt;Dispatcher, SomeObject&gt; data = tuple as Tuple&lt;Dispatcher, SomeObject&gt;;
              Window window = new WPFWindow(data.Item1, data.Item2);
              System.Windows.Threading.Dispatcher.Run();
              this.tmp = 0;
          });
      thread.SetApartmentState(System.Threading.ApartmentState.STA);
      thread.IsBackground = true;
      thread.Start(new Tuple&lt;Dispatcher, SomeObject&gt;(Dispatcher.CurrentDispatcher, someObject));
  }
  </code></pre>
  
  <p>So, I put a break along the statement "this.tmp = 0;" and it doesn't get hit when I close the MFC application.  Is it safe to assume that the Dispatcher is not being shutdown, but the thread is being aborted?</p>
  
  <p>If the thread is aborted, what are the consequences?</p>
  
  <p>Update:</p>
  
  <p>On another project, I ran into a problem where the GC doesn't seem to be doing its job.  It turns out, it's related to a Dispatcher started on a background thread that is not being shutdown.  The WPF application's memory usage just kept increasing every time a task is ran on background thread.  So, be sure to invoke shutdown on Dispatchers created on a background thread whether you created a Dispatcher object explicitly or not.</p>
  
  <p>Not invoking shutdown on Dispatcher created on background thread will cause memory/resource leak.  Dispatcher objects hang onto resources.  Hence, the GC aren't able to clean them up.</p>
  
  <p>To make sure that a dispatcher is shut down properly, in my case, I have to spawn the background thread from the MFC side of the application then have the main thread wait on it before it completely shuts down.  As Hans Passant pointed out, MFC doesn't wait unless it is explicitly told.</p>