Implementation #1 - using Parallel loop
var client = new HttpClient();
var processes = new List<Task<object>>();
Parallel.ForEach(urls, url =>
{
processes.Add(client.GetAsync(url).Result.Content.ReadAsAsync<object>());
});
Task.WhenAll(processes);
Implementation #2 - using async method + Result
var client = new HttpClient();
var processes = new List<Task<object>>();
urls.ForEach(url =>
{
processes.Add(GetChain(client, url));
});
Task.WhenAll(processes);
async Task<object> GetChain(HttpClient client, string url)
{
return await client.GetAsync(url).Result.Content.ReadAsAsync<object>();
}
Implementation #3 - using async method + await
var client = new HttpClient();
var processes = new List<Task<object>>();
urls.ForEach(url =>
{
processes.Add(GetChain(client, url));
});
Task.WhenAll(processes);
async Task<object> GetChain(HttpClient client, string url)
{
var chain = await client.GetAsync(url);
return await chain.Content.ReadAsAsync<object>();
}
I like implementation #1 with Parallel loop, but there is a possibility that Parallel will create a new thread on each iteration and will consume more resources.
Questions
- Is there a difference between these methods, can I keep using Parallel.ForEach?
- If Parallel loop is bad, how can I improve it without creating a separate "async" method?
- Is "await method.Result" the same as "await method1 await method2", #2 vs #3?
P.S. There are two "await" calls because HttpClient requests data, then read it asynchronously.
Extra question - are these lines the same?
method1.Result.method2 // get result immediately
method1.ContinueWith(data => data.Result.method2) // call both methods first