我应该如何在线程之间同步?
考虑以下应用程序架构:
UI(视图)线程创建一个 ViewModel。
ViewModels 构造函数请求业务逻辑对象(提供者)开始从存储中检索数据。
它通过订阅提供者的 DataRecieved 事件并调用 StartRetreeringData() 方法来完成此操作。
提供程序在 StartRetreeringData() 方法主体中创建一个后台线程,循环获取的数据,并在循环主体中引发 DataRecieved 事件,将实际数据对象作为自定义 EventArgs 公共字段传递。
链接到 DataRecieved 事件的 ViewModel 方法然后更新 UI 元素绑定到的 observableCollection。
问题是:
MVVM 实现这样的架构一切正常吗?
我应该在什么时候进行线程同步,即调用 Deployment.Current.Dispatcher 来分派源自后台线程的调用来更新 UI?
Consider the following app architecture:
UI (View) Thread creates a ViewModel.
ViewModels constructor requests business logic object (provider) to start retrieving data from storage.
It does it by subscribing to DataRecieved event of the provider and calls the StartRetrievingData() method.
Provider creates a background thread in the StartRetrievingData() method body, loops through the obtained data and in the loop body raises DataRecieved event, passing actual data object as a custom EventArgs public field.
A ViewModel method, that is linked to a DataRecieved event then updates the observableCollection, that UI element is bound to.
Questions are:
Is everything ok with such architecture as MVVM implemntation?
At what point should I do the thread synchronization, that is calling Deployment.Current.Dispatcher to dispatch the call originated from a background thread to update the UI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我个人会处理 ViewModel 中的所有同步要求。
如果 View 正在构造 ViewModel,则 TPL 为此提供了一个很好的机制:
这种方法的好处是您不必将 WPF 相关类型(例如
Dispatcher
)引入到你的 ViewModel 层,它工作得非常干净。I would, personally, handle all synchronization requirements in your ViewModel.
If the View is constructing the ViewModel, the TPL provides a nice mechanism for this:
The nice thing with this approach is that you don't have to pull in the WPF related types (such as
Dispatcher
) into your ViewModel layer, and it works very cleanly.