There is this question that mentions to use async/await to prevent deadlocks. In my case, this code works fine just for 2 or 3 elements in elementsInList variable showed below. I would like to know if there is a quantity factor that could affect to raise or not the deadlock.
I'm trying to use the following block of code:
var responses = elementsInList.AsParallel()
.WithDegreeOfParallelism(elementsInList.Count)
.Select(elementInList => GetResponse(elementInList, timeout)).ToList();
(...)
public JObject GetResponse(JObject request, TimeSpan timeout)
{
var endpoint = ConfigurationManager.AppSettings.Get("MyEndPoint");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.Timeout = timeout;
IList<MediaTypeFormatter> formatters = GetMediaTypeFormatters();
HttpResponseMessage response = client.PostAsJsonAsync(EndPoint, request).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<T>(formatters).Result;
}
throw new Exception(response.ReasonPhrase);
}
}
catch (Exception ex)
{
return new JObject()
{
new JProperty("Exception", "Invalid response. " + ex.Message)
};
}
}
If I debug the code, when the .AsParallel line is hit, code gets blocked and it never returns an answer or goes to the next line. It seems a deadlock is happening there.
A detail I want to add, if I use this code with 2 or 3 elements, it works fine, however, when the call is like 30-50 elements, it fails. Is there a quantity factor that could raise the deadlock in the second scenario and not in the first one? I'm very curious if it affects or not, or if it also could be generated with only 2 or 3 elements.