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

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

Patricia Arquette
Release: 2025-01-21 02:37:07
Original
544 people have browsed it

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

Thread safety of C# Random.Next() method

C#'s Random.Next() method is not thread-safe. Using the same Random instance from multiple threads may result in unpredictable behavior, or even returning a result of all 0's.

Solution

To create a thread-safe version of Random we can create local instances for each thread. The following code demonstrates this:

<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>
Copy after login

This class maintains a separate static Random variable (_local) for each thread. To prevent conflicts between instances created at the same time, use global static Random instances (_global) to seed thread-local instances.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template