Runtime: Add ParallelOptions constructor with MaxDegreeOfParallelism parameter

Created on 22 Aug 2019  路  4Comments  路  Source: dotnet/runtime

ParallelOptions could use a new constructor with a single parameter for MaxDegreeOfParallelism.

Rationale and Usage

Most of the use cases for ParallelOptions end up changing the MaxDegreeOfParallelism property, either via Create-Set-Call or using the object initializer.

ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 8;

Parallel.ForEach(list, options, action);
ParallelOptions options = new ParallelOptions()
{
    MaxDegreeOfParallelism = 8
};

Parallel.ForEach(list, options, action);

// or

Parallel.ForEach(list, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, action);

This constructor would make the usage of ParallelOptions less of a hassle and inlining it in Parallel's For or ForEach would involve less complex syntax ({}, =,...).

Parallel.For(0, 100, new ParallelOptions(8), action);
Parallel.ForEach(list, new ParallelOptions(8), action);

Proposed API

public partial class ParallelOptions
{
+    public ParallelOptions(int maxDegreeOfParallelism) { }
}
area-System.Linq.Parallel

All 4 comments

I am seeing this is reasonable to avoid setting the max property every time you create the ParallelOptions object.

I am expecting for anyone writing a clear code would call the constructor as

```C#
ParallelOptions options = new ParallelOptions(maxDegreeOfParallelism: 8);

So comparing this to 

```C#
    ParallelOptions options = new ParallelOptions() { MaxDegreeOfParallelism = 8 };

Wouldn't have much benefit more than saving typing '''{}'''

From using this API a few dozen times I have to say that this MaxDegreeOfParallelism is the exact thing that I wanted to set in 95% of the cases.

Elevating a single option to the constructor (as opposed to elevating all of them) is a bit of an impurity on this API. Also, you could set one value through the ctor and override it using a property initializer. That would be a usage error and a pit fall.

IMO, these small impurities are worth the convenience in this case.

@GSPP thanks for the feedback. the issue is already marked ready for the design review.

Video

  • After more discussion, it seems we prefer the current state because it's less ambiguous.
Was this page helpful?
0 / 5 - 0 ratings