所以我有这个命令:
public DelegateCommand GenerateReportForAllClientsCommand {获得; set ; } public bool CanExecuteGenerateReportForAllClients() { 返回 true ; } 公共 异步 空隙 GenerateReportForAllClientsExecute() { if (ClientList.Count < 1 ) return ; IsGenerating = true ; await Task.WhenAll(clientList.Select(i = > ReportManager .GeneratePdfReportAsync(i.Client))); IsGenerating = false ; }和此方法: public static async 任务GeneratePdfReportAsync(ClientInfoModel client) { // 生成客户的pdf报告... }
问题是,当我调用命令时,我的应用程序冻结了,我不希望它这样做...当我在这样做一个单一的报告时,这不会发生其他命令:
public async void GenerateReportExecute() { IsGenerating = true ; await ReportManager.GeneratePdfReportAsync(SelectedClient); IsGenerating = false ; }上述方法完美按预期工作,在生成文件时,应用程序仍然可用。当我使用 Task.WhenAll ?
async 不再起作用了>解决方案通过搜索网络,我找到了一个方便的答案来解答我的问题。 我还有另一个我的 GeneratePdfReportAsync 方法中的异步 / 等待,我发现任务或任务< T> 对象需要UI线程可用。但是对于这种方法,我不需要UI线程,但它仍然访问它以验证我的任务的结果,因此阻止我的UI直到我的所有任务完成。 解决方案是在 GeneratePdfReportAsync 方法的其他方法的等待期间,我添加了 ConfigureAwait(false) 女巫告诉任务不调用UI。 消息= 等待 ClientInfoManager.GetMessagesFromClientAsync(客户端, true )。ConfigureAwait( false );
由于C#上异步和并行编程的非常有用的教程,我找到了解决问题的方法。 链接: 第1部分 第2部分
So I have this command :
public DelegateCommand GenerateReportForAllClientsCommand { get; set; } public bool CanExecuteGenerateReportForAllClients() { return true; } public async void GenerateReportForAllClientsExecute() { if (ClientList.Count < 1) return; IsGenerating = true; await Task.WhenAll(clientList.Select(i => ReportManager.GeneratePdfReportAsync(i.Client))); IsGenerating = false; }and this method :
public static async Task GeneratePdfReportAsync(ClientInfoModel client) { // Generates a pdf report of the client... }The problem is that when I call the command my application freezes, which I don't want it to do... This doesn't happen when I do a single report like so in this other command:
public async void GenerateReportExecute() { IsGenerating = true; await ReportManager.GeneratePdfReportAsync(SelectedClient); IsGenerating = false; }The method above works perfectly as expected, while generating the file, the application is still available. Does anyone know why async doesn't work anymore when I use Task.WhenAll ?
解决方案 By searching the web, I found a convenient answer to my problem. I had an other async / await in my GeneratePdfReportAsync method, and I've discovered that a Task or Task<T> object need the UI Thread to be available. But in this case for this method, I didn't need the UI Thread, but it was still accessing it to verify the result of my task and so blocking my UI until all my tasks were finished. The solution was that during the await from other method in the GeneratePdfReportAsync method, I've added ConfigureAwait(false) witch tells the Task not to call the UI. messages = await ClientInfoManager.GetMessagesFromClientAsync(client, true).ConfigureAwait(false);I've found the solution to my problem thanks to a very helpful tutorial for asynchronous and parallel programming on C#. Links : Part 1 Part 2
更多推荐
异步并行任务不起作用
发布评论