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

时间:2011-09-12 19:28:21

标签: c# .net multithreading architecture mvvm

考虑以下应用架构:

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

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

它通过订阅提供者的DataRecieved事件并调用StartRetrievingData()方法来实现。

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

一个ViewModel方法,链接到DataRecieved事件,然后更新该UI元素绑定的observableCollection。

问题是:

MVVM实现这样的架构一切都好吗?

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

1 个答案:

答案 0 :(得分: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
    });
}

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

相关问题