2013-05-17 67 views
1

我想通過使用Mvvm模式的進度指示器傳遞DocumentViewer上的一些內容,這一代會在從db異步獲取數據後使用UiElements。的async/await使用Mvvm訪問UI線程與異步/等待

public async void ProcessReportAsync(){ 

     IsBusy = true; 

     _reportDal = new ReportDal(_sprocName,_sprocParams); 
     ReportContainers = new ObservableCollection<ReportContainerViewModel>(); 

     await Task.Run(() => _reportDal.InitReportDal()); 
     ReportDataTable = _reportDal.DataTableReport; 

     await Task.Run(() => ProcessedElements()); 

     var t3 = Task.Run(() => ProcessPage(_reportPage)); 
     var t4 = Task.Run(() => ProcessContainerData()); 
     await Task.WhenAll(t3, t4); 
     var p = new PrinterViewModel(this); 

     // This statement does'nt complete its execuation, which is adding more UIElements 
     if(DispatcherHelper.UIDispatcher.CheckAccess()) { 

      DispatcherHelper.UIDispatcher.Invoke(
       ()=>_document = p.CreateDocument(new Size(p.PrintDialog.PrintableAreaWidth,p.PrintDialog.PrintableAreaHeight)) 
       ,DispatcherPriority.Background); 

     } 
    // Can't reach this code 
     IsBusy = false; 


    } 

回答

1

一個好的方面是,它需要派遣回給你正確的上下文的照顧。

public async Task ProcessReportAsync() 
{ 
    IsBusy = true; 

    _reportDal = new ReportDal(_sprocName,_sprocParams); 
    ReportContainers = new ObservableCollection<ReportContainerViewModel>(); 

    await Task.Run(() => _reportDal.InitReportDal()); 
    ReportDataTable = _reportDal.DataTableReport; 

    await Task.Run(() => ProcessedElements()); 

    var t3 = Task.Run(() => ProcessPage(_reportPage)); 
    var t4 = Task.Run(() => ProcessContainerData()); 
    await Task.WhenAll(t3, t4); 
    var p = new PrinterViewModel(this); 

    _document = p.CreateDocument(new Size(p.PrintDialog.PrintableAreaWidth,p.PrintDialog.PrintableAreaHeight)); 

    IsBusy = false; 
} 

我建議你閱讀我的async/await intro和我MSDN article on async

+0

非常感謝Stephen,DocumentViewer的內容現在顯示出來。但IsBusy道具運行不正常,看起來Ui沒有響應並同步運行。我會閱讀你的文章。 –