title: Using SynchronizationContext for sending events back to the UI for WinForms or WPF
body: <p>I'm using a SynchronizationContext to marshal events back to the UI thread from my DLL that does a lot of multi-threaded background tasks.</p>
  
  <p>I know the singleton pattern isn't a favorite, but I'm using it for now to store a reference of the UI's SynchronizationContext when you create foo's parent object.</p>
  
  <pre><code>public class Foo
  {
      public event EventHandler FooDoDoneEvent;
  
      public void DoFoo()
      {
          //stuff
          OnFooDoDone();
      }
  
      private void OnFooDoDone()
      {
          if (FooDoDoneEvent != null)
          {
              if (TheUISync.Instance.UISync != SynchronizationContext.Current)
              {
                  TheUISync.Instance.UISync.Post(delegate { OnFooDoDone(); }, null);
              }
              else
              {
                  FooDoDoneEvent(this, new EventArgs());
              }
          }
  
      }
  }
  </code></pre>
  
  <p>This didn't work at all in WPF, the TheUISync instances UI sync (which is feed from the main window) never matches the current SynchronizationContext.Current.  In windows form when I do the same thing they will match after an invoke and we'll get back to the correct thread.</p>
  
  <p>My fix, which i hate, looks like</p>
  
  <pre><code>public class Foo
  {
      public event EventHandler FooDoDoneEvent;
  
      public void DoFoo()
      {
          //stuff
          OnFooDoDone(false);
      }
  
      private void OnFooDoDone(bool invoked)
      {
          if (FooDoDoneEvent != null)
          {
              if ((TheUISync.Instance.UISync != SynchronizationContext.Current) &amp;&amp; (!invoked))
              {
                  TheUISync.Instance.UISync.Post(delegate { OnFooDoDone(true); }, null);
              }
              else
              {
                  FooDoDoneEvent(this, new EventArgs());
              }
          }
  
      }
  }
  </code></pre>
  
  <p>So I hope this sample makes enough sense to follow.</p>