I am using Parallel.ForEach
loop to download multiple files from a Web API in parallel, in a .NET 4.8 application.
The problem is that sometimes I get a ThreadAbortException
/ The Maximum Wait/Sleep/Join time has been exceeded (00:05:00).
I can't seem to find a way to extend the "Maximum Wait Timeout" for the treads inside the Parallel.ForEach
loop.
Sample code causing the problem.
// create the httpclient
using (HttpClient httpClient = new HttpClient())
{
// now try to get documents in a parallel threaded task.
Parallel.ForEach(documentIds,
new ParallelOptions { MaxDegreeOfParallelism =
Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.50) * 2.0))},
(documentId) =>
{
try
{
// post the data to the service
using (HttpResponseMessage response =
httpClient.PostAsync(serviceURL, new StringContent(
requestBody.ToString())).GetAwaiter().GetResult())
{
// show error if service failed
if (response.IsSuccessStatusCode == false)
{
throw new Exception("Error getting content. " +
response?.ReasonPhrase);
}
// get back content
using (Stream responseStream = response.Content.ReadAsStreamAsync()
.GetAwaiter().GetResult())
{
// write the file to the FileSystem
}
}
}
catch (Exception ex)
{
// eat the error
// NOTE: This does catch the ThreadAbortException but it breaks out
// of the Parallel.ForEach BUT I want it to continue with other documents
}
});
}
Update 1
I got it to work but the solution is not a good one.
Basically the HttpClient is the problem.
If I create a NEW HttpClient inside the Parallel.ForEach loop, then it will let me handle the ThreadAbortException without breaking out of the loop.
MS best practices says to not create multiple HttpClients else it can keep to many open sockets before cleanup.