Is Random.Next not Thread-Safe and returns 0 in .netcore

Solution 1:

If you run the following console application (RELEASE build), you should see occasional sequences of zeros in the output.

It doesn't happen for every random value, but when it happens, you get quite a few zeroes in a row:

static class Program
{
    static void Main()
    {
        var rng = new Random(12345);

        Parallel.Invoke(
            () => test(rng),
            () => test(rng),
            () => test(rng),
            () => test(rng),
            () => test(rng),
            () => test(rng),
            () => test(rng),
            () => test(rng));
    }

    static void test(Random rng)
    {
        int[] numbers = new int[10000];

        for (int i = 0; i < numbers.Length; ++i)
            numbers[i] = rng.Next();

        for (int i = 0; i < numbers.Length; ++i)
            Console.WriteLine(numbers[i]);
    }
}

Note that it doesn't happen (or happens a lot less) for a DEBUG build; this is the nature of threading errors.

It doesn't even happen on every run for a RELEASE build, but it does happen sometimes (on my PC).