开发者

WPF Multithreaded UI - Usercontrols

开发者 https://www.devze.com 2023-02-06 17:31 出处:网络
I have seen some code samples of multi-threaded UIs in WPF using multiple windows where each window runs on it\'s own UI thread. I\'m curious though - is there a way to accomplish this with embedded c

I have seen some code samples of multi-threaded UIs in WPF using multiple windows where each window runs on it's own UI thread. I'm curious though - is there a way to accomplish this with embedded controls?

For example lets say I have usercontrol1 开发者_运维技巧and usercontrol2 both embedded in Window1. Usercontrol1 starts to spin and blocks the main UI thread. The window and usercontrol2 are effected. Is there a way to make it so even if usercontrol1 blocks, Window1 + usercontrol2 are still responsive?

Let us assume we don't control the developers of usercontrol1 - so we can't tell them to make their control behave.

Let us also assume the exchange of data between usercontrol1 + 2 is a must.

Should I be exploring something like AddIn's?


You can't "run" the controls on another thread (as with Winforms, the controls themselves must be created and run on the same thread as the top-level parent), but there's nothing stopping you from initiating actions on another thread from a user control. You just have to ensure that you use the Dispatcher to Invoke any operations that will have a direct effect upon the control itself. Behind-the-scenes processing can be done entirely on another thread, though; it's just the physical updating of the UI that has to be invoked back via the Dispatcher.

EDIT: After the question was edited, no, there is no way to move all of the "work" that a particular component performs to another thread. If you can't control the development of the component in question, then you're at the mercy of the developer and where he decides to execute the code.


As on the top you have visual (Window) which is inheriting from DispatcherObject. It is designed as STA threading model, in which single thread is accessing the object methods and properties.

That is why both controls must be created in the same thread as Window.

If you need to exchange data between controls and you are not controlling developers of those controls I would consider using PRISM or other MVVM framework. In prism you have EventAggregator which is basically subscriber publisher pattern your UserControl1 can publish something and the other one if it's subscribed will receive that.

0

精彩评论

暂无评论...
验证码 换一张
取 消