tags:

views:

258

answers:

4

can anyone tell me if the C# Random.Next() method is thread safe?

+7  A: 

There's nothing special done in the Next method to achieve thread safety. However, it's an instance method. If you don't share instances of Random across different threads, you don't have much to worry about.

Jon has nice posts on this subject:

StaticRandom
Revisiting randomness

Mehrdad Afshari
+2  A: 

No, it's not thread safe. If you need to use the same instance from different threads, you have to synchronise the usage.

I can't really see any reason why you would need that, though. It would be more efficient for each thread to have their own instance of the Random class.

Guffa
+1  A: 

Per documentation

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

http://msdn.microsoft.com/en-us/library/system.random.aspx

Seattle Leonard
A: 

For thread safe random number generator look at RNGCryptoServiceProvider

Yassir
How is a random number generator being cryptographically secure related to thread-safety?
dtb
And `RandomNumberGenerator` is much slower as well (and doesn't easily give you integers).
Callum Rogers
The documentation you linked to specifically states that the crypto RNG is *not* thread safe.
Eric Lippert
oh don't know how that happend sorry anyway i corrected the answer :)
Yassir
Yeah the RNGCryptoServiceProvider is gold. Much better than Random, though there is a bit more legwork to make it spit out a particular type of number (since it generates random bytes).
Rangoric
@Rangoric: No, it's not better than Random for any purpose where either can be used. If you need randomness for encryption purposes the Random class is not an option, for any purpose where you can choose, the Random class is faster and easier to use.
Guffa
@Guffa ease of use is a one time thing though as I already stuffed it into a library, so is not really a good point. Being faster is a valid point, though I'd rather have the real randomness as opposed to looks good randomness. And for that I also get to have it be thread safe. Although now I intend to test this to see how much slower it is (Random produces doubles and converts them to what you ask for so it may even depend on exactly what number range you need)
Rangoric
In C# I am finding that with a very basic RNGCrypto implementation it's about 100:1 depending on the exact number being looked for (127 does twice as good as 128 for instance). Next I plan to add threading and see how it does (why not :) )
Rangoric
Update to above statement. I got it to a 2:1 for ranges of under 256 values, and does better the closer to a factor of 256 the number we want is.
Rangoric