使用Mvvm使用async / await访问UI线程

时间:2013-05-17 01:36:53

标签: mvvm

我想使用Mvvm模式在DocumentViewer上传递一些带有进度指示器的内容,这一代将在从异步数据库获取数据后使用UiElements。

    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 个答案:

答案 0 :(得分:1)

async / await的一个不错的方面是它负责为您调度回正确的上下文。

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