Language
Edit

CA1876: Do not use 'AsParallel' in 'foreach'

Property Value
Rule ID CA1876
Title Do not use AsParallel in foreach
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 No
Enabled by default in .NET 11 As suggestion
Applicable languages C# and Visual Basic

Cause

A foreach loop enumerates the result of calling AsParallel() directly.

Rule description

The foreach statement processes each item serially. Calling AsParallel on the collection doesn't make the loop run in parallel.

How to fix violations

Remove AsParallel() if the loop should run serially. To process each item in parallel, use ForEach. To parallelize LINQ query operations, call AsParallel() before those operations, then enumerate the query or call ForAll.

Examples

The following code shows a violation of CA1876:

var values = new[] { 1, 2, 3 };
foreach (var value in values.AsParallel())
    Console.WriteLine(value);
Dim values = {1, 2, 3}
For Each value In values.AsParallel()
    Console.WriteLine(value)
Next

To process each item in parallel, use Parallel.ForEach. Use this approach only when the work can run concurrently; it doesn't preserve item order.

var values = new[] { 1, 2, 3 };
Parallel.ForEach(values, value => Console.WriteLine(value));
Dim values = {1, 2, 3}
Parallel.ForEach(values, Sub(value) Console.WriteLine(value))

When to suppress warnings

Suppress the warning only when you use AsParallel() for another reason. The foreach loop itself still runs serially.

Suppress a warning

To suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1876
// The code that's violating the rule is on this line.
#pragma warning restore CA1876

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1876.severity = none

For more information, see How to suppress code analysis warnings.

See also