The body of Parallel.For or Parallel.ForEach adds to a List, Dictionary or HashSet declared outside it, which is not thread-safe

tx0/csharp:parallel-loop-shared-collectionrecommendedwarningreliability/collectionsdepth fastbug

What it finds

The iterations of a parallel loop run on several threads at once. List<T>, Dictionary<TKey, TValue> and HashSet<T> allow only one writer at a time; concurrent Add calls lose elements or corrupt the collection. A concurrent collection, a lock, or collecting per iteration and merging afterwards avoids it.

From the rule's source, parallel_loop_shared_collection.rs.

Example from the rule's tests
using System.Collections.Generic;using System.Threading.Tasks; class Batch{    void Run(int[] items)    {        List<int> results = new List<int>();        Parallel.ForEach(items, i => results.Add(i * 2));tx0 reports: results is a List<int> changed from several threads at once        Parallel.ForEach(items, i =>        {            lock (results)            {                results.Add(i);            }        });    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:parallel-loop-shared-collection" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:parallel-loop-shared-collection] reason="..."

tx0 explain tx0/csharp:parallel-loop-shared-collection shows the same in the terminal. Found a false positive? Report it.