Is C#’s Random.Next() method thread safe?
Is C#’s Random.Next() method thread safe?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s nothing special done in the
Nextmethod to achieve thread safety. However, it’s an instance method. If you don’t share instances ofRandomacross different threads, you don’t have to worry about state corruption within an instance. Do not use a single instance ofRandomacross different threads without holding an exclusive lock of some sort.Jon Skeet has a couple nice posts on this subject:
StaticRandomRevisiting randomness
As noted by some commentators, there is another potential problem in using different instances of
Randomthat are thread-exclusive, but are seeded identically, and therefore induce the identical sequences of pseudorandom numbers, because they may be created at the same time or within close temporal proximity of each other. One way to alleviate that issue is to use a masterRandominstance (which is locked by a single thread) to generate some random seeds and initialize newRandominstances for every other thread to use.