12

Can somebody tell me when to use a Dispatcher and when to use the SynchronizationContext class?

For a while now I have been using the Dispatcher to queue up tasks from a background thread, then I discovered the SynchronizationContext.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
ash 2010
  • 329
  • 2
  • 9

2 Answers2

17

AFAIK, when using WPF, the SynchronizationContext.Current object is of type DispatcherSynchronizationContext which is actually just a wrapper around the Dispatcher object and the Post and Send methods just delegate to Dispatcher.BeginInvoke and Dispatcher.Invoke.

So even if you decide to use SynchronizationContext I think you end up calling dispatcher behind the scenes.

Besides I think it is a bit cumbersome to use SynchronizationContext as you have to pass a reference to the current context to all threads that need to call into your UI.

Jakob Christensen
  • 14,826
  • 2
  • 51
  • 81
4
  1. Use the Dispatcher when your code is tightly coupled to WPF.

  2. Use the AsyncOperationManager when you need to queue something on the 'Context' thread. This works with Windows Forms, ASP .NET and WCF applications as well.

  3. Avoid using the SynchronizationContext yourself. The AsyncOperationManager uses this mechnism internally.

jbe
  • 6,976
  • 1
  • 43
  • 34
  • I realise you've written this answer some time ago. Nevertheless, I would be very interested if you could provide a concrete example how to use `AsyncOperationManager` to queue a delegate for execution on the "context" (UI) thread. I know how `SynchronizationContext` works; but I can't figure out how `AsyncOperation` is supposed to work. (I currently have the notion that it's rather like a "token" for keeping track of a asynchronous operation's state and progress, but won't help with actually scheduling a delegate for execution.) – stakx - no longer contributing Jan 31 '11 at 20:07
  • 1
    How to use AsyncOperationManager: http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx – jbe Jan 31 '11 at 21:06
  • What if you need to synchronously run something on the UI thread? AsyncOperation doesn't have a Send() method but SynchronizationContext does. – Monstieur Jun 07 '13 at 11:29