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

Max*_*lov 3 .net c# architecture multithreading mvvm

考虑以下应用程序架构:

UI(视图)线程创建一个ViewModel.

ViewModels构造函数请求业务逻辑对象(提供程序)开始从存储中检索数据.

它通过订阅提供程序的DataRecieved事件并调用StartRetrievingData()方法来完成.

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

链接到DataRecieved事件的ViewModel方法然后更新UI元素绑定的observableCollection.

问题是:

MVVM实现这样的架构一切正常吗?

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

Ree*_*sey 6

我个人会在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
    });
}
Run Code Online (Sandbox Code Playgroud)

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