Sunday, January 8, 2012

WPF : Implementation of DoEvents feature

When we are doing heavy operations on UI thread, it doesn't update UI changes untill its freed to do that. To overcome that we had DoEvents in VB6 which used to let UI thread updates UI and then come back to do heavy operation.
Here I am going to show an implementation of that feature.

I have an application class, where I start with a frame which is created when application begins, and whenever you call DoEvents it creates 1 more frame and forces Dispatcher to complete all pending frames between application started frame and end frame.

public class Application
    {
        private static readonly DispatcherOperationCallback exitFrameCallback = ExitFrame;
 
 
        private static Object ExitFrame(Object state)
        {
            var frame = state as DispatcherFrame;
 
            // Exit the nested message loop.
            frame.Continue = false;
            return null;
        }
 
        public static void DoEvents()
        {
            // Create new nested message pump.
            var nestedFrame = new DispatcherFrame();
 
            // Dispatch a callback to the current message queue, when getting called,
            // this callback will end the nested message loop.
            // note that the priority of this callback should be lower than the that of UI event messages.
            DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
                DispatcherPriority.Background, exitFrameCallback, nestedFrame);
 
            // pump the nested message loop, the nested message loop will
            // immediately process the messages left inside the message queue.
            Dispatcher.PushFrame(nestedFrame);
 
            // If the "exitFrame" callback doesn't get finished, Abort it.
            if (exitOperation.Status != DispatcherOperationStatus.Completed)
            {
                exitOperation.Abort();
            }
        }
 
    }


Now from any part of your application you can simply put following code and it will make sure that UI thread updates the UI.

Application.DoEvents();

No comments:

Post a Comment