title: What is the preferred way to get code to execute in a WPF GUI thread?
body: <p>I have a main thread that contains my WPF GUI and one or more background threads that occassionally need to execute code in the main thread asynchronously (e.g. a status update in the GUI).</p>
  
  <p>There are two ways (that I know of, maybe more) to accomplish this:</p>
  
  <ol>
  <li>by scheduling a task using the <code>TaskScheduler</code> from the target thread's synchronization context, and</li>
  <li>by invoking a delegate using the <code>Dispatcher</code> from the target thread.</li>
  </ol>
  
  <p>In code:</p>
  
  <pre class="lang-cs prettyprint-override"><code>using System.Threading.Tasks;
  using System.Threading;
  
  Action mainAction = () =&gt; MessageBox.Show(string.Format("Hello from thread {0}", Thread.CurrentThread.ManagedThreadId));
  Action backgroundAction;
  
  // Execute in main thread directly (for verifiying the thread ID)
  mainAction();
  
  // Execute in main thread via TaskScheduler
  var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  backgroundAction = () =&gt; Task.Factory.StartNew(mainAction, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
  Task.Factory.StartNew(backgroundAction);
  
  // Execute in main thread via Dispatcher
  var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
  backgroundAction = () =&gt; dispatcher.BeginInvoke(mainAction);
  Task.Factory.StartNew(backgroundAction);
  </code></pre>
  
  <p>I like the TPL-based version, because I already use TPL a lot and it provides me with a lot of flexibility, e.g. by waiting on the task or chaining it with other tasks. However, in most examples of WPF code I have seen so far, the Dispatcher variant was used.</p>
  
  <p>Assuming I didn't need any of that flexibility and only wanted to execute some code in the target thread, what are the reasons one would prefer one way over the other? Are there any performance implications?</p>