Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatcher and SynchronizationContext classes

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.

like image 394
ash 2010 Avatar asked Jun 18 '10 13:06

ash 2010


2 Answers

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.

like image 82
Jakob Christensen Avatar answered Sep 17 '22 16:09

Jakob Christensen


  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.

like image 41
jbe Avatar answered Sep 20 '22 16:09

jbe