I have a number of questions regarding the operation of a Parallel.ForEach
loop, especially in regards to the setting of theParallelOptions.MaxDegreeOfParallelism
property.
My computer's CPU is Quad core featuring 8 logical processors.
To me the following should be the maximum number of possible process that can be performed in work in parallel as after all, I have 8 threads available:
ParallelOptions parallelOptions = new()
{
MaxDegreeOfParallelism = Environment.ProcessorCount //8,
};
Consider the following code. This simply iterates around a list of 300 uri's and does "something" with the responses:
List<string> uriList = new List<string>();
for (int i = 0; i < 300; i++)
{
uriList.Add(uri);
}
HttpClient httpClient = new HttpClient();
ParallelOptions parallelOptions = new()
{
MaxDegreeOfParallelism = uriList.Count(),
};
await Parallel.ForEachAsync(uriList, parallelOptions, async (uri, token) =>
{
var response = await httpClient.GetStringAsync(uri);
if (response != null)
{
ProcessResponse(response);
}
});
Note that the MaxDegreeOfParallelism
property is set to the size of the uriList
i.e 300 rather than the thread count available to me from my physical hardware of 8. This code works and I'm lost to why setting the MaxDegreeOfParallelism
property that high "works".
Questions:
The
MaxDegreeOfParallelism
property can be specified to any number but the maximum amount of concurrent operations will only ever be as high as the hardware's available thread count?The
MaxDegreeOfParallelism
property can be though of as setting how many parallel "batches" of work will be carried out concurrently? For example iterating round a list of 16 items with aMaxDegreeOfParallelism
set to '8' will causes two batches of '8' concurrent calls?If the
MaxDegreeOfParallelism
property isn't set then by default the maximum number of threads avaliable will be set?In the situation of an asynchronous
Parallel.Foreach
do procedding requests wait until the previous "batched" calls have returned? Or, when anawait
is encountered and a thread is "freed" can another item in theuriList
begin its logical steps in the loop?Is there a "sweet spot" for the setting of the
MaxDegreeOfParallelism
property?