Below is sample console app and output is
Output is different each time and is fine but it needs to complete all tasks before I print result.
It seems that Parallel.ForEachAsync
is not waiting for all tasks to be completed. Am I missing anything here ?
internal class Program
{
private async static Task Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
await TestParallel();
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed);
Console.ReadLine();
}
private static async Task TestParallel()
{
var tests = new List<int>() { 1, 2, 3, 4, 5, 6 };
var options = new ParallelOptions { MaxDegreeOfParallelism = 5,
CancellationToken = CancellationToken.None };
var responses = new List<string>();
await Parallel.ForEachAsync(tests, options, async (testno, cancellationToken) =>
{
var response = await TestTask(testno);
responses.Add(response);
});
foreach (var response in responses)
{
Console.WriteLine(response);
}
}
private static Task<string> TestTask(int testno)
{
System.Threading.Thread.Sleep(1000);
return Task.FromResult($"Test{testno}");
}
}