Why do UI Controls in WPF have Thread Affinity?

前端 未结 2 1766
清歌不尽
清歌不尽 2020-12-01 23:56

Why is it that the thread that created the control is the one that can update it? Why didn\'t MS give people the ability to use locking and other thread synchronization tech

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 00:26

    WPF, like virtaully all UI toolkits, works by pumping a message loop. Since messages can come at any time and affect any control you would need a global lock. And to make it less error prone you probably want a function that would invoke a delegate under the lock. Perhaps something like this:

    Dispatcher.Invoke(Delegate, Object())
    

    The fact that this gets marshalled to the UI thread instead of acquiring a global lock is just an implementation detail.

提交回复
热议问题