简体   繁体   English

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

[英]How should I synchronize between threads?

Consider the following app architecture: 考虑以下应用程序架构:

UI (View) Thread creates a ViewModel. UI(视图)线程创建一个ViewModel。

ViewModels constructor requests business logic object (provider) to start retrieving data from storage. ViewModels构造函数请求业务逻辑对象(提供程序)开始从存储中检索数据。

It does it by subscribing to DataRecieved event of the provider and calls the StartRetrievingData() method. 它通过订阅提供程序的DataRecieved事件并调用StartRetrievingData()方法来完成。

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. Provider在StartRetrievingData()方法体中创建后台线程,循环获取所获得的数据,并在循环体中引发DataRecieved事件,将实际数据对象作为自定义EventArgs公共字段传递。

A ViewModel method, that is linked to a DataRecieved event then updates the observableCollection, that UI element is bound to. 链接到DataRecieved事件的ViewModel方法然后更新UI元素绑定的observableCollection。

Questions are: 问题是:

Is everything ok with such architecture as MVVM implemntation? MVVM实现这样的架构一切正常吗?

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? 我应该在什么时候进行线程同步,即调用Deployment.Current.Dispatcher来调度源自后台线程的调用以更新UI?

I would, personally, handle all synchronization requirements in your ViewModel. 我个人会在ViewModel中处理所有同步要求。

If the View is constructing the ViewModel, the TPL provides a nice mechanism for this: 如果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
    });
}

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. 这种方法的好处在于您不必将与WPF相关的类型(例如Dispatcher )引入到ViewModel层中,并且它可以非常干净地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM