Home >Backend Development >C++ >Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?

Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 02:46:13244browse

Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?

Thread safety of C# random number generator

Is the

method in C# thread-safe and allows multiple threads to be used concurrently? The answer is unfortunately no. Using the same instance in multiple threads may result in data corruption, manifested by returning consecutive 0s. Random.Next()

Fortunately, it is possible to create a thread-safe variant without using a cumbersome lock on every

call. Drawing on concepts presented in an enlightening article, we offer a solution: Next()

<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>
The core of this approach is to maintain a separate static

instance for each thread. But even this simple implementation faces another pitfall. When multiple instances are initialized within a short period of time (around 15 milliseconds), they default to the same sequence. To solve this problem, we introduce a global static Random instance specifically used to generate seeds for each thread. Random

The article mentioned above provides illustrative code that details both of these considerations and provides in-depth guidance on the intricacies of

in C#. Random

The above is the detailed content of Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?. 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