我应该如何在线程之间同步?

发布于 2024-12-04 05:42:46 字数 480 浏览 0 评论 0原文

考虑以下应用程序架构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2024-12-11 05:42:46

我个人会处理 ViewModel 中的所有同步要求。

如果 View 正在构造 ViewModel,则 TPL 为此提供了一个很好的机制:

TaskFactory uiFactory;

public YourViewModel()
{
     // Since the View handles the construction here, you'll get the proper sync. context
     uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
}

// In your data received event:
private items_DataReceived(object sender, EventArgs e)
{
    uiFactory.StartNew( () =>
    {
        // update ObservableCollection here... this will happen on the UI thread
    });
}

这种方法的好处是您不必将 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:

TaskFactory uiFactory;

public YourViewModel()
{
     // Since the View handles the construction here, you'll get the proper sync. context
     uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
}

// In your data received event:
private items_DataReceived(object sender, EventArgs e)
{
    uiFactory.StartNew( () =>
    {
        // update ObservableCollection here... this will happen on the UI thread
    });
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文