[英]How should I synchronize between threads?
考慮以下應用程序架構:
UI(視圖)線程創建一個ViewModel。
ViewModels構造函數請求業務邏輯對象(提供程序)開始從存儲中檢索數據。
它通過訂閱提供程序的DataRecieved事件並調用StartRetrievingData()方法來完成。
Provider在StartRetrievingData()方法體中創建后台線程,循環獲取所獲得的數據,並在循環體中引發DataRecieved事件,將實際數據對象作為自定義EventArgs公共字段傳遞。
鏈接到DataRecieved事件的ViewModel方法然后更新UI元素綁定的observableCollection。
問題是:
MVVM實現這樣的架構一切正常嗎?
我應該在什么時候進行線程同步,即調用Deployment.Current.Dispatcher來調度源自后台線程的調用以更新UI?
我個人會在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層中,並且它可以非常干凈地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.