Wednesday, November 3, 2010

SynchronizationContext, a multithreaded UI best friend

Of course we are all waiting for the new async features in C# 5 as announced by Anders Hejlsberg at PDC 2010.(Download the Visual Studio Async CTP), implementing a set of changes to the C# language that support a new pattern for asynchronous programming. In the meanwhile we still have to do it the old fashion way by executing work on background threads and marshalling the results back to the main UI thread. One very important player in this story are the different implementations of the SynchronizationContext class.

Depending on the kind of application, different implementations are used.

  • Windows Forms: System.Windows.Forms.WindowsFormsSynchronizationContext, used by the GUI thread(s) in Windows Forms applications. Other threads in the same application may use different SynchronizationContext implementations.
  • Windows Presentation Foundation and Silverlight: System.Windows.Threading.DispatcherSynchronizationContext, used by the GUI thread(s) in Windows Presentation Foundation and Silverlight applications. Other threads in the same application may use different SynchronizationContext implementations.
  • ASP.NET: System.Web.AspNetSynchronizationContext, used by threads running in an application hosted by the ASP.NET runtime.
  • Other: System.Threading.SynchronizationContext. Used by ThreadPool and Thread class threads, Windows Services, and Console applications, unless that thread replaces the default with a different SynchronizationContext