I am using Parallel.ForEach to execute about 2200 requests (httpClient.GetAsync) so I can get the data needed faster. While sometimes this process passes without exception often I end up with AggregateException (InnerException:"A task was cancelled").
Cancel() is not called and I am using the default request Timeout.
There are suggestions to remove the using of the HttpClient creation and use a single instance of it, but it did not help.
Any ideas what causes the exception and how to prevent it?
public void GetData()
{
ConcurrentBag<MyItem> alltems = new ConcurrentBag<MyItem>();
Parallel.For(0, listOfUrls, url =>
{
allItems.Add(MyMethod(this.Get(url));
}
}
public HttpResponseMessage Get(string url)
{
httpClient = NewHttpClient();
{
var requestContent = httpClient.GetAsync(this.siteUrl + "/" + url).Result;
return requestContent;
}
}
HttpClient cachedHttpClient;
private HttpClient NewHttpClient(bool skipAuthorization = false)
{
var h = new WebRequestHandler();
if (cachedHttpClient == null)
{
var client = new HttpClient(h);
if (!skipAuthorization)
{
client.DefaultRequestHeaders.Add("Authorization", "WRAP access_token=" + accessToken);
}
return client;
}
else
{
return cachedHttpClient;
}
}