gpt4 book ai didi

mvvm - 使用异步访问 UI 线程/使用 Mvvm 等待

转载 作者:行者123 更新时间:2023-12-03 10:38:08 25 4
gpt4 key购买 nike

我想使用 Mvvm 模式在带有进度指示器的 DocumentViewer 上传递一些内容,这一代将在从 db 异步获取数据后使用 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;


}

最佳答案

async 的一个很好的方面/await是它负责为您分派(dispatch)回正确的上下文。

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 .

关于mvvm - 使用异步访问 UI 线程/使用 Mvvm 等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com