Per my understanding the Parallel.Foreach block the calling thread until it completes. However, the below code behave differently --
private void TestParallel()
{
Console.WriteLine("Starting TestParallelForEach");
TestParallelForEach();
Console.WriteLine("Ending TestParallelForEach");
}
public void TestParallelForEach()
{
List<string> urls = new List<string>();
urls.Add("http://www.google.com");
urls.Add("http://www.yahoo.com");
urls.Add("http://www.microsoft.com");
urls.Add("http://www.facebook.com");
var t = Parallel.ForEach(
urls,
new ParallelOptions { MaxDegreeOfParallelism = 1 },
async url =>
{
string x = await openUrlAsync(url);
Console.WriteLine(string.Format("Url {0}, result {1}", url, x));
});
Console.WriteLine(" Parallel.ForEach Completed - " + t.IsCompleted);
}
private async Task<string> openUrlAsync(string url)
{
var client = new HttpClient();
//var result = await client.GetAsync("http://webcode.me");
var result = await client.GetAsync(url);
string re = result.StatusCode.ToString();
Console.WriteLine(string.Format("Got response from Url {0}", url));
return re;
}
However, the output of the above code is as follows --
Starting TestParallelForEach
Parallel.ForEach Completed - True
Ending TestParallelForEach
Got response from Url www.facebook.com
Url www.facebook.com, result OK
Got response from Url www.stanford.edu
Url www.microsoft.com, result OK
My expectation was the output should be in the below order since Parallel.Foreach block the calling thread until it completed.
Starting TestParallelForEach
Got response from Url www.facebook.com
Url www.facebook.com, result OK
Got response from Url www.stanford.edu
Url www.microsoft.com, result OK
Parallel.ForEach Completed - True
Ending TestParallelForEach
I reckon I am missing something here ....why doesn't Parallel.Foreach waits till all it's internal tasks(the Http call here) are completed ?