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:
Mehrdad Afshari
2010-06-15 22:19:18
+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
2010-06-15 22:28:51
+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.
Seattle Leonard
2010-06-15 22:35:03
A:
For thread safe random number generator look at RNGCryptoServiceProvider
Yassir
2010-06-15 22:37:41
How is a random number generator being cryptographically secure related to thread-safety?
dtb
2010-06-15 22:45:38
And `RandomNumberGenerator` is much slower as well (and doesn't easily give you integers).
Callum Rogers
2010-06-15 22:58:34
The documentation you linked to specifically states that the crypto RNG is *not* thread safe.
Eric Lippert
2010-06-15 23:00:04
oh don't know how that happend sorry anyway i corrected the answer :)
Yassir
2010-06-15 23:07:39
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
2010-06-16 05:05:24
@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
2010-06-16 06:06:15
@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
2010-06-16 14:08:29
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
2010-06-16 14:44:33
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
2010-06-16 15:55:22