title: WPF Threading - Can someone explain what's going on here?
body: <p>DISCLAIMER: The following code is not something I would ever use in a real application. I stumbled on this problem and would like to know what's happening under the hoods.</p>
  
  <p>Let's assume that for some crazy reason we had the following code...</p>
  
  <pre><code>using (System.Net.WebClient webClient = new System.Net.WebClient())
  {
      bool done = false;
      webClient.UploadFileCompleted += (s, e) =&gt; done = true;
  
      string uploadUri = "ftp://www.notarealurl.com/";
      string file = @"temp.txt";
  
      webClient.UploadFileAsync(
          new Uri("ftp://www.notarealurl.com/"), "temp.txt");
  
      while (!done)
      {
          System.Threading.Thread.Sleep(100);
      }
  }
  </code></pre>
  
  <p>This code works as expected in a simple console app. However, move it to a WPF app and it never exits the "while" loop. This through me for a loop for a while until it occured to me that this might be an issue with the events being dropped in the message pump and therefor not being processed. To test this, I modified the "while" loop like this...</p>
  
  <pre><code>while (!done)
  {
      System.Threading.Thread.Sleep(100);
  
      // Processes all messages currently in the message queue
      Dispatcher.Invoke(
          DispatcherPriority.Background, new ThreadStart(delegate { }));
  }
  </code></pre>
  
  <p>Sure enough, that fixed it. So,on to the question...</p>
  
  <p>What is going on here? When I run this code in a console app the event handler is executed on a worker thread. Why/how does it get put on the main thread in WPF?</p>