Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So I have this command :
C#
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 :
C#
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:
C#
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 ?
Posted
Updated 7-Aug-14 2:27am
v2

1 solution

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.

C#
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
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900