Random number generator returning zeros

后端 未结 1 1551
眼角桃花
眼角桃花 2020-12-19 23:30

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

相关标签:
1条回答
  • 2020-12-20 00:30

    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

    0 讨论(0)
提交回复
热议问题