Confusion about Refreshing the UI in WPF

2019-02-24 09:08发布

问题:

I have heard that this refreshes the UI but why so? Dispatcher invokes this empty action and thats it there is no call InvalidateMeasure() which would trigger the UI to re-measure and re-arrange and re-render inside the action. Where is here the measure and arrange process to update/refresh the UI?

private static Action EmptyDelegate = delegate() { };

public static void Refresh(UIElement uiElement)
{
   uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}

Any help?

EDITED: I want to know the details why is UI rendered. Answers like well that triggers ui update are not helping me any further guys.

回答1:

Microsoft recommends a slighty different way of doing what your code does using PushFrame.

The code has nothing to do with rendering. What it does is similar to the DoEvents method known from VB6 and WinForms. DoEvents halts the program while pumping the Windows message queue and handling the messages in the queue. This includes any rendering messages such as WM_PAINT and WM_NCPAINT.

The code instructs the Dispatcher to halt the current thread and pump its queue and handle all messages that have a priority of DispatcherPriority.Render or higher. If there are any pending rendering messages in the queue, for example if InvalidateRect has been called somewhere by the framework, these messages will be handled and the UI will be re-rendered.

DoEvents has always been considered a code smell because it bypasses the message queue. If you want a responsive user interface you should use worker threads instead.



回答2:

This can be used to force WPF to update the UI because of the priority of the invocation. Since this invoke uses the Dispatcher synchronously, any tasks that are already queued with an equal or higher priority than DispatcherPriority.Render will be run before running the delegate you provided.

Here is the list of potential values of DispatcherPriority, and it explains the order tasks are run by the dispatcher.