I have code that loads data from multiple sources using async methods (shown below).
public class ThEnvironment
{
public async Task LoadLookupsAsync(CancellationToken cancellationToken) { ... }
public async Task LoadFoldersAsync(CancellationToken cancellationToken) { ... }
}
Elsewhere in my program, I want to load multiple environments.
ThEnvironment[] workingEnvironments = ThEnvironment.Manager.GetWorkingEnvironments();
foreach ( ThEnvironment environment in workingEnvironments )
{
await environment.LoadLookupsAsync(CancellationToken.None);
await environment.LoadFoldersAsync(CancellationToken.None);
}
My question is twofold:
- For any single environment, how would I run both environment.Load...Async() methods in parallel and still be able to pass the CancellationToken?
- How would I do this for all environments in parallel?
Bottom line: I'd like to run all Load..Async() methods for all environments in parallel and still be able to pass the CancellationToken.
update
Thanks to everyone for the very quick answers. I've reduced the code down to the following:
Refresh();
var tasks = ThEnvironment.Manager.GetWorkingEnvironments()
.SelectMany(e => new Task[] { e.LoadLookupsAsync(CancellationToken.None), e.LoadFoldersAsync(CancellationToken.None) });
await Task.WhenAll(tasks.ToArray());
I'm not too concerned about capturing all exceptions since this is not a production application. And the Refresh() at the top took care of the form's initial painting issue.
Great stuff all around.