Skip windows messages when forcing execution of the Dispatcher queue

695 views Asked by At

I am currently forced to update some part of the UI while some lengthy operation is performed on the UI thread. I know this should not be done, but - as I said - I am forced...

I have therefore added the following call to the location where the UI should be updated:

Dispatcher.Invoke(() => { }, DispatcherPriority.Render);

As you may know, this will force the Dispatcher Queue to be processed until all queued delegates up to (and including) priority Render have been executed. This way, the UI is updated although the UI thread is currently blocked.

Now, my problem is: When calling the Invoke method, the dispatcher queue does not only contain the delegates for re-rendering the UI, but obviously it also contains some custom Windows message. This Windows message is generated by our own application and it will be executed during the Invoke call. However, I do not want this because it introduces weird side effects! I only want the UI to be redrawn.

Is there any way to force UI rendering without processing any other Windows messages?

I tried to achieve this by calling some Win API functions:

private static readonly uint MSG1 = 0xC21E;
private static readonly uint MSG2 = 0xC25D;

// ...

while (PeekMessage(out msg, IntPtr.Zero, MSG1, MSG2, (uint)PeekMessageParams.PM_REMOVE))
{
    TranslateMessage(ref msg);
    DispatchMessage(ref msg);
}

MSG1 and MSG2 are messages that I found when I inspected the messages in the queue while the UI is blocked and my UI updates are done. I assumed that these messages have something to do with re-rendering the UI, but that assumption is not correct obviously. At least, the UI is not refreshed with the above code.

Any other ideas?


EDIT:
I just found the Dispatcher.Yield() method which was introduced in .NET 4.5. The documentation says:

Use this method if want to give your app a chance to process events while your app is doing a lot of work on the UI thread. For example, you can use this method in a long-running loop that updates a control.

Does anybody have any experience with this method?

0

There are 0 answers