Search code examples
c#asynchronouswindows-8.1-universal

Run multiple await at the same time


I have a code that looks something like this:

firstList = await GetFirstListFilesAsync();
textBlock1.Text = "found " + firstList.Count + " first list's results";
secondList = await GetSecondListFilesAsync();
textBlock2.Text = "found " + secondList.Count + " second list's results";
thirdList = await GetThirdListFilesAsync();
textBlock3.Text = "found " + thirdList.Count + " third list's results"

So now it gets first list, sets first TextBlock text, then it gets second list, sets second TextBlock text and then gets third list and sets third TextBlock text. But I would like that all await operations would run simultaneously, so all TextBlocks would update more or less at the same time. Or maybe not at the same time - each TextBlock would update as the corresponding await method finishes. Anyway, what I want to achieve here, is to get results faster. if I run those methods one by one, they wait until the previous is finished, but if they would run all at the same time, third method would return the result faster, right? So my question is - is that possible? And if yes, then how?


Solution

  • I think this is what you are looking for:

    var tasks = new Task<MyMethodReturnObject>[3];
    tasks[0] = GetFirstListFilesAsync();
    tasks[1] = GetSecondListFilesAsync();
    tasks[2] = GetThirdListFilesAsync();
    
    // At this point, all three tasks are running at the same time.
    
    // Now, we await them all.
    await Task.WhenAll(tasks);
    
    // Get an individual result, where result is MyMethodReturnObject
    var myText = tasks[0].Result;
    
    // Loop through results
    var results = tasks.Select(o => o.Result).ToList();
    foreach (var result in results)
    {
        Console.Write(result);
    }
    

    Source: http://blog.stephencleary.com/2012/02/async-and-await.html