Random.Next() sometimes returns same number in separate threads

前端 未结 3 1708
别那么骄傲
别那么骄傲 2020-12-06 17:44

I have the following class

class Program
{
   static Random _Random = new Random();

   static void Main(string[] args)
   {
      ...
      for (int i = 0;          


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 18:30

    Random is not thread-safe - you shouldn't be using the same instance from multiple threads. It can get much worse than just returning the same data - by using it from multiple threads, you can get it "stuck" in a state where it will always return 0, IIRC.

    Obviously you don't just want to create a new instance for each thread at roughly the same time, as they'll end up with the same seeds...

    I have an article which goes into the details of this and provides an implementation which lazily instantiates one instance of Random per thread using an incrementing seed.

提交回复
热议问题