WPF uses a dedicated UI thread to complete the operation and update of the interface, which associates a unique Dispatcher object for scheduling work item queues in a prioritized order. Application.Run () is actually an indirect call to Dispatcher.run ().
Dispatcher processes work item queues by looping, which is often used as a "frame (dispatcherframe)". Dispatcher.run () Creates and launches this frame, which is also the ultimate way for Application.Run () to start the message loop.
public sealed class Dispatcher
{
[SecurityCritical, UIPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public static void Run()
{
PushFrame(new DispatcherFrame());
}
}
DispatcherFrame can be nested and determine whether the loop continues by checking the Continue property. We can terminate all frame loops by calling Dispatcher.exitallframes (), which, of course, is not desirable and may cause some unexpected occurrences.
The Dispatcher scheduling object corresponds to the Dispatcherobject, where most of the controls are inherited from Dispatcherobject and even application. These inherited Dispatcherobject objects have thread affinity features, meaning that only those object instances are created and Dispatcher threads (usually the default UI thread) can be updated directly.
When we try to update a label from a non-UI thread, we see an exception like the following.
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(() => this.label1.Content = DateTime.Now.ToString()).Start();
}
In accordance with the dispatcherobject principle, we use Window.Dispatcher.Invoke () to successfully complete this update operation.
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
this.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => this.label1.Content = DateTime.Now.ToString()));
}).Start();
}
If in other projects, such as class libraries, we can do the same thing with Application.Current.Dispatcher.Invoke (...), they all point to the UI Thread Dispatcher this unique object.
Dispatcher also provides this asynchronous version of BeginInvoke.
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
Thread.Sleep(3000);
this.label1.Content = DateTime.Now.ToString();
}));
MessageBox.Show("Hi!");
}).Start();
}
With all the exceptions, WPF also provides a type that inherits from Freezable, although Freezable indirectly inherits from Dispatcherobject, but when such an object changes from a modified state to a frozen state, it becomes a free thread object and does not have a thread association. (Refer to MSDN for Freezable details)