concept SynchronizationContext in category .net

appears as: SynchronizationContext
Rx.NET in Action

This is an excerpt from Manning's book Rx.NET in Action.

In the .NET Framework, SynchronizationContext is an object that handles the synchronization of work for a specific threading context, such as the UI thread in WPF and WinForms or an ASP.NET request. By using SynchronizationContext, you can dispatch work from a source thread to a target thread and let SynchronizationContext handle the details.

SynchronizationContextScheduler in Rx provides a bridge between the Rx schedulers’ model and the .NET SynchronizationContext model so that each scheduled task is posted on SynchronizationContext. When creating the SynchronizationContextScheduler, you need to pass the SynchronizationContext you want to use. For example:

var syncContextScheduler = new SynchronizationContextScheduler(
                                  SynchronizationContext.Current);

In both WinForms and XAML platforms, SynchronizationContext plays a big part because if you try to run code that interacts with the UI component from a thread different than the UI thread, an exception is thrown. So every operation related to the UI needs to go through the right SynchronizationContext. In WinForms, you can use the control itself to invoke the actions on the right thread:

The ContextDisposable class wraps a disposable object and executes its Dispose method on a specified SynchronizationContext. Executing the Dispose method on a SynchronizationContext is important when the operation is tied to a specific context (for example, when changing a UI element). This code creates a StartBusy method to create a disposable that turns off the busy indicator on the UI’s SynchronizationContext: