Application.DoEvents In WPF Revisited

|

A long time ago, I blogged about how to implement the Application.DoEvents logic in WPF, Windows Forms has this method for the very beginning, but WPF doesn't build this logic into the framework, I think WPF team made a good decision here, because as I've mentioned in my original blog article, nested message pump is evil. But at some rare circumstances, DoEvents can solve some of the problems such as how to expand TreeViewItems as I've blogged ages ago.

Recently, I just find another way to implement the DoEvents method, and this version of DoEvents only requires a single line of code:

using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace Sheva.Windows
{
    /// <summary>
    /// Designates a Windows Presentation Foundation application with added functionalities.
    /// </summary>
    public class WpfApplication : Application
    {
        /// <summary>
        /// Processes all messages currently in the message queue.
        /// </summary>
        /// <remarks>
        /// This method can potentially cause code re-entrancy problem, so use it with great care.
        /// </remarks>
        public static void DoEvents()
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
        }
    }
}

Actually, Dispatcher.Invoke will do proper nested pumping for you when the priority is anything than DispatcherPriority.Send.

0 comments: