I would expect this code to take 1 second to execute:
public async void Test()
{
DateTime start = DateTime.Now;
await Parallel.ForEachAsync(new int[1000], new ParallelOptions { MaxDegreeOfParallelism = 1000 }, async (i, token) =>
{
Thread.Sleep(1000);
});
Console.WriteLine("End program: " + (DateTime.Now - start).Seconds + " seconds elapsed.");
}
Instead, it takes 37 seconds on my pc (i7-9700 8-core 8-thread):
End program: 37 seconds elapsed.
I am generating 1000 tasks with MaxDegreeOfParallelism = 1000....why don't they all run simultaneously?
The
Parallel.ForEachAsyncmethod invokes the asynchronousbodydelegate onThreadPoolthreads. Usually this delegate returns aValueTaskquickly, but in your case this is not what happens, because your delegate is not really asynchronous:You are probably getting here a compiler warning, about an
asyncmethod lacking anawaitoperator. Nevertheless giving a mixed sync/async workload to theParallel.ForEachAsyncmethod is OK. This method is designed to handle any kind of workload. But if the workload is mostly synchronous, the result might be a saturatedThreadPool.The
ThreadPoolis said to be saturated when it has already created the number of threads specified by theSetMinThreadsmethod, which by default is equal toEnvironment.ProcessorCount, and there is more demand for work to be done. In this case theThreadPoolswitches to a conservative algorithm that creates one new thread every second (as of .NET 6). This behavior is not documented precisely, and might change in future .NET versions.In order to get the behavior that you want, which is to run the delegate for all 1000 inputs in parallel, you'll have to increase the number of threads that the
ThreadPoolcreates instantly on demand:Some would say that after doing so you won't have a thread pool any more, since a thread pool is meant to be a small pool of reusable threads. But if you don't care about the semantics and just want to get the job done, whatever the consequences are regarding memory consumption and overhead at the operating system level, that's the easiest way to solve your problem.