Understanding the WPF Dispatcher.BeginInvoke

后端 未结 2 1030
小蘑菇
小蘑菇 2021-01-01 16:26

I was under the impression that the dispatcher will follow the priority of the operations queued it and execute the operations based on the priority or the orde

相关标签:
2条回答
  • 2021-01-01 16:54

    This is because the first MessageBox is blocking the UI thread.

    What Dispatcher.BeginInvoke() is doing under the hood is taking your delegate and scheduling it to be run on the main UI thread during it's next idle period. However, MessageBox will block whichever thread it is called from until it is closed. This means that the second MessageBox cannot be displayed until the first is cleared because the UI thread scheduler sees that the thread is already in use (waiting for the first MessageBox to be cleared) and can't execute the next delegate containing the second MessageBox.

    0 讨论(0)
  • 2021-01-01 16:59

    Before coming down to your code behavior it's a prerequisite to understand the priorities of Dispatcher. DispatcherPriority is divided into ranges as shown in below image.

    If you simply queue 4 actions to 4 above ranges on Dispatcher. the Foreground queue will get executed first, then the Background and then in last Idle queue. priority 0 will not get executed.

    Now your code:

    Three task are queued 1st in background, 2nd in background and 3rd in foreground queue. So 3rd will get executed first. then 2nd task cause it has higher priority then 1st task. I hope that clears it.

    Although some more observation will help you understand it better like, what if you have set the priorities as 7,8 and 9. So as this is a foreground queue, 7 will get executed first then 7 and then 8. One by one and exclusively in that order and while 7 is getting executed, 8 and 9 will wait, meaning foreground queue will get executed synchronously to each another.

    But Background and Idle queue will not behave in that way the where execution is asynchronous to other tasks and tasks will follow the priority. And first Background and the Idle queue.

    Hope this explanation clarifies to some extent.

    0 讨论(0)
提交回复
热议问题