Reading WPF Source Code series(1) - DispatcherSynchronizationContext
WPF requires STA threading.
One of the changes to the threading support that shipped in the .Net Framework 2.0 was the introduction of SynchronizationContext.
The purpose of this class is to provide a model to make communication between threads easier and more robust.
I find that there is a great article on codeproject discussion about this class:
The .NET Framework's New SynchronizationContext Class(https://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx)
And WPF use this class to deal with concurrency management. It create a inherited class called DispatcherSynchronizationContext.
(Before you go to DispatcherSynchronizationContext, please read the article about SynchronizationContext class carefully)
/// <summary>
/// Constructs a new instance of the DispatcherSynchroniazationContext
/// using the current Dispatcher.
/// </summary>
public DispatcherSynchronizationContext() : this(Dispatcher.CurrentDispatcher)
{
}
/// <summary>
/// Constructs a new instance of the DispatcherSynchroniazationContext
/// using the specified Dispatcher.
/// </summary>
public DispatcherSynchronizationContext(Dispatcher dispatcher)
{
if(dispatcher == null)
{
throw new ArgumentNullException("dispatcher");
}
_dispatcher = dispatcher;
// Tell the CLR to call us when blocking.
SetWaitNotificationRequired();
}
/// <summary>
/// Synchronously invoke the callback in the SynchronizationContext.
/// </summary>
public override void Send(SendOrPostCallback d, Object state)
{
_dispatcher.Invoke(DispatcherPriority.Normal, d, state);
}
/// <summary>
/// Asynchronously invoke the callback in the SynchronizationContext.
/// </summary>
public override void Post(SendOrPostCallback d, Object state)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, d, state);
}
In the book Essential Windows Presentation Foundation of page 426, author gives us an example of how to using SynchronizationContext to deal the communication between the UI thread and a background thread.
if you have interesting, you can check it.
update: There is another article about SynchronizationContext: Using SynchronizationContexts
(https://blogs.msdn.com/mattdotson/archive/2006/02/13/531315.aspx)
Comments
- Anonymous
July 28, 2008
PingBack from http://blog.a-foton.ru/2008/07/reading-wpf-source-code-series1-dispatchersynchronizationcontext/