Search code examples
c#azure-functionsparallel.foreach

Azure Function - Increase Environment.ProcessorCount


I have an Azure Function in which I am doing a POST call to an api endpoint and I am doing this using:

Parallel.ForEach(activations, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, act =>
    {
        //api call here
    });

For a while, I was running this locally and I decided to check the value of Environment.ProcessorCount in a deployed Function and the value returned was 2.

The plans are to use functions on a Consumption plan.

Is it possible to increase the value of this variable? I tried to add the application key FUNCTIONS_WORKER_PROCESS_COUNT with a value of 4, but the result still returned 2 (to be honest, I don't know if this setting is the same thing as the Env.ProcessCount).

Many thanks!


Solution

  • If you use .Net 6 or up you can use the DOTNET_PROCESSOR_COUNT environment variable to override the number of processors thought to be available by the .NET runtime and reported by the Environment.ProcessorCount property.

    For example, if you set DOTNET_PROCESSOR_COUNT to 4, Environment.ProcessorCount will disregard any process affinity and CPU utilization limit and return 4.

    (source)

    However, if you do that only to set MaxDegreeOfParallelism, why not just do

    Parallel.ForEach(activations, 
        new ParallelOptions { MaxDegreeOfParallelism = X }, 
        act =>
        {
            //api call here
        });