I have an ASP.NET application that relies on the Random class to generate a pseudo-random string. It uses the following code (this is part of a larger piece of sample code
The Random
class is not thread-safe.
If you generate random numbers on the same instance on multiple threads at once, its internal state will be corrupted and it will start returning zeroes.
You need to make the Random
instance [ThreadStatic]
to ensure that each instance is not shared by multiple threads.
Note that initializers for [ThreadStatic]
fields will only run once, so you need to check whether it's null
every time you use the field and initialize it if necessary.
It would also be a good idea to include both the thread ID and the current time in the seed to prevent seed collisions.
Note, by the way, that the Random
class is not secure; consider using the RNGCryptoServiceProvider class