Select Page

For random draws inside a parallel loop, use Random.Shared when you want a convenient shared generator. An ordinary new Random() instance needs synchronization if multiple threads access it. A loop that happens to finish without suspicious values does not establish that the shared instance is safe.

This .NET 10 console experiment compares three choices using eight logical workers and 200,000 dice draws per worker. It checks the results without requiring the unsafe choice to fail. The complete program below was compiled and run on .NET 10.0.13.

Choose who owns the generator

The Random API documentation requires synchronized access to ordinary instances used by multiple threads. The separate Random.Shared contract explicitly permits concurrent calls from any thread.

Choice Ownership in this example Use
One ordinary Random Every worker receives the same unsynchronized object Deliberate unsafe comparison; do not use this pattern in production
Random.Shared Every worker accesses the documented thread-safe generator The convenient choice for concurrent draws here
ThreadLocal<Random> The factory creates a generator for each accessing thread An alternative when you want to manage per-thread ownership

ThreadLocal<T> returns a thread-specific value. Here the factory creates a fresh object, and that object stays inside synchronous loop bodies on that thread. Sharing the returned object elsewhere would break this ownership rule. The container is disposed only after the loop completes; its documentation excludes concurrent disposal from the thread-safety guarantee.

Measure two observable symptoms

Each mode performs 1,600,000 calls to Next(1, 7). The upper bound is exclusive, so valid results are 1 through 6, as described in the Random range guidance. The program records out-of-range values and counts each consecutive run of at least 1,000 identical values once.

A run belongs to one logical worker. It never joins draws from different workers or separate loop bodies. A stretch of 1,001 identical values counts as one long run, not two. Fixed-input self-checks exercise the detector before any random draws.

These counters are alarms, not a statistical randomness test or a proof of generator correctness. In particular, an in-range generator stuck on one face would escape the range check. The long-run check targets that symptom, but cannot diagnose its cause. A long run is possible for a functioning random generator too; rejecting one is this experiment’s deliberately strict anomaly policy, not an API guarantee.

Run the complete program

With a .NET 10 SDK installed, create a console project:

dotnet new console --framework net10.0 --name RandomConcurrency

Replace its entire Program.cs with this program:

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

const int workers = 8;
const int drawsPerWorker = 200_000;

// Check the detector independently of unpredictable random draws.
Stats boundary = Inspect(() => 1, 999);
Stats longRun = Inspect(() => 1, 1_001);
Stats invalid = Inspect(() => 7, 3);
if (boundary.LongRuns != 0 || longRun.LongRuns != 1 || invalid.Outside != 3)
    throw new InvalidOperationException("Detector self-check failed.");
Console.WriteLine("Detector self-checks passed.");
Console.Error.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}");
Console.Error.WriteLine("Eight logical workers; 200000 draws each; maximum concurrency 8.");

var ordinary = new Random();
Measure("ordinary shared Random", () => ordinary, false);
Measure("Random.Shared", () => Random.Shared, true);
using (var perThread = new ThreadLocal<Random>(() => new Random()))
{
    Measure("ThreadLocal<Random>", () => perThread.Value!, true);
}
Console.WriteLine("All thread-safe mode assertions passed.");

void Measure(string name, Func<Random> getRandom, bool assertNoAnomalies)
{
    var results = new Stats[workers];
    Parallel.For(0, workers, new ParallelOptions { MaxDegreeOfParallelism = workers }, worker =>
    {
        Random random = getRandom();
        // Each loop body owns its counters and previous-value state.
        results[worker] = Inspect(() => random.Next(1, 7), drawsPerWorker);
    });

    int outside = results.Sum(result => result.Outside);
    int longRuns = results.Sum(result => result.LongRuns);
    int draws = results.Sum(result => result.Draws);
    Console.Error.WriteLine($"{name}: draws={draws}, outside={outside}, longRuns={longRuns}");
    if (draws != workers * drawsPerWorker)
        throw new InvalidOperationException($"{name}: draw count failed.");
    if (assertNoAnomalies && (outside != 0 || longRuns != 0))
        throw new InvalidOperationException($"{name}: anomaly detected.");
}

static Stats Inspect(Func<int> next, int count)
{
    int outside = 0;
    int longRuns = 0;
    int previous = 0;
    int runLength = 0;
    for (int draw = 0; draw < count; draw++)
    {
        int value = next();
        if (value < 1 || value > 6)
            outside++;
        runLength = draw > 0 && value == previous ? runLength + 1 : 1;
        if (runLength == 1_000)
            longRuns++; // Count a maximal run once, even if it continues.
        previous = value;
    }
    return new Stats(count, outside, longRuns);
}

readonly record struct Stats(int Draws, int Outside, int LongRuns);

Run it with observations redirected to a separate file:

dotnet run --project RandomConcurrency 2> observations.txt

The expected application stdout is exactly:

Detector self-checks passed.
All thread-safe mode assertions passed.

The program throws if either safe mode triggers an alarm or if any mode completes the wrong draw count. It intentionally makes no zero-anomaly assertion about the ordinary shared instance. An exception prevents the final success line and fails the run.

Read the observations without overclaiming

Our verified run recorded the following application observations on stderr. This is one observed result, not an expected transcript for future runs:

Runtime: .NET 10.0.13
Eight logical workers; 200000 draws each; maximum concurrency 8.
ordinary shared Random: draws=1600000, outside=0, longRuns=0
Random.Shared: draws=1600000, outside=0, longRuns=0
ThreadLocal<Random>: draws=1600000, outside=0, longRuns=0

The ordinary instance produced no detected anomaly here. That changes neither its documented contract nor the need to synchronize it. Scheduling, runtime implementation, and available CPU resources affect what this experiment can expose. Eight loop bodies with a maximum concurrency of eight do not guarantee eight simultaneous physical threads. The verification container had a one-CPU quota, so this run is especially limited as evidence about contention.

The two safe modes also produced no detected anomalies and passed their assertions. That supports the reported observations; their thread-safety guarantees come from the documentation. The per-worker counters and result slots keep the measurement state separate, so counting does not introduce a shared increment race.

For this synchronous parallel workload, choose Random.Shared unless you need explicit per-thread ownership. If you retain one ordinary instance, synchronize every access consistently. See lock, Monitor and SemaphoreSlim for choosing a gate, and the controlled race-condition tutorial for a deterministic lost-update demonstration. This experiment measures no timings and makes no speed comparison.

Share This