Inside the Parallel.ForEach
method when I use an asynchronous method DownloadWebsiteAsync
to get an external resource the calling method executeAsync_Click
does not await the RunDownloadParallelAsync
method and prints the result before RunDownloadParallelAsync
finishes its work.
When I change DownloadWebsiteAsync
to DownloadWebsiteSync
(which works in a synchronous way) everything is working well.
private async void executeAsync_Click(object sender, RoutedEventArgs e)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var results = await DemoMethods.RunDownloadParallelAsync();
PrintResults(results);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
resultsWindow.Text += $"Total execution time: { elapsedMs }";
}
public static async Task<List<WebsiteDataModel>> RunDownloadParallelAsync()
{
List<string> websites = PrepData();
List<WebsiteDataModel> output = new List<WebsiteDataModel>();
await Task.Run(() =>
Parallel.ForEach<string>(websites, async (site) =>
{
WebsiteDataModel results =await DownloadWebsiteAsync(site);
output.Add(results);
})
);
return output;
}