Home >Backend Development >C++ >Is C#'s `Random.Next()` Method Thread-Safe, and How Can We Create a Thread-Safe Alternative?

Is C#'s `Random.Next()` Method Thread-Safe, and How Can We Create a Thread-Safe Alternative?

Linda Hamilton
Linda HamiltonOriginal
2025-01-21 02:35:09875browse

Is C#'s `Random.Next()` Method Thread-Safe, and How Can We Create a Thread-Safe Alternative?

Thread safety guarantee in C# random number generation

In multi-threaded applications, it is crucial to ensure that critical resources or methods are thread-safe. In C#, the thread safety of the Random.Next() method of the commonly used random number generation tool is of concern.

Is C#’s random number generator thread-safe?

No, concurrent use of Random.Next() from multiple threads at the same time is not thread-safe. This can lead to unpredictable behavior and possibly incorrect results. The root cause of the problem is that multiple threads may try to modify the internal state of the same Random instance at the same time, causing the value to become corrupted or even fail completely, returning only 0.

Create a thread-safe random number generator

While Random.Next() itself is not thread-safe, it is possible to create a thread-safe version without using a complex locking mechanism for every method call. By leveraging a technique described in an external article, we can implement a custom ThreadSafeRandom class:

<code class="language-csharp">public class ThreadSafeRandom
{
    private static readonly Random _global = new Random();
    [ThreadStatic] private static Random _local;

    public int Next()
    {
        if (_local == null)
        {
            int seed;
            lock (_global)
            {
                seed = _global.Next();
            }
            _local = new Random(seed);
        }

        return _local.Next();
    }
}</code>

Explanation

The

ThreadSafeRandom class ensures thread safety by maintaining a separate Random instance for each thread. This prevents threads from interfering with each other's internal state. However, there is a caveat: creating multiple instances of Random in very close proximity (within about 15 milliseconds) may result in the same sequence of random numbers. To solve this problem, we introduce a global static Random instance (_global) that is used to generate the seed value for each thread's local Random instance (_local).

The above is the detailed content of Is C#'s `Random.Next()` Method Thread-Safe, and How Can We Create a Thread-Safe Alternative?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn