Is C# Random Number Generator thread safe?

2019-01-02 23:53发布

Is C#'s Random.Next() method is thread safe?

11条回答
一夜七次
2楼-- · 2019-01-03 00:21

UPDATED: It is not. You need to either reuse an instance of Random on each consecutive call with locking some "semaphore" object while calling the .Next() method or use a new instance with a guaranteed random seed on each such call. You can get the guaranteed different seed by using cryptography in .NET as Yassir suggested.

查看更多
干净又极端
3楼-- · 2019-01-03 00:24

Since Random isn't thread-safe, you should have one per thread, rather than a global instance. If you're worried about these multiple Random classes being seeded at the same time (i.e. by DateTime.Now.Ticks or such), you can use Guids to seed each of them. The .NET Guid generator goes to considerable lengths to ensure non-repeatable results, hence:

var rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0))
查看更多
乱世女痞
4楼-- · 2019-01-03 00:26

The offical answer from Microsoft is a very strong no. From http://msdn.microsoft.com/en-us/library/system.random.aspx#8:

Random objects are not thread safe. If your app calls Random methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0.

As described in the docs, there is a very nasty side effect that can happen when the same Random object is used by multiple threads: it just stops working.

(i.e. there is a race condition which when triggered, the return value from the 'random.Next....' methods will be 0 for all subsequent calls.)

查看更多
太酷不给撩
5楼-- · 2019-01-03 00:26

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.

查看更多
迷人小祖宗
6楼-- · 2019-01-03 00:26

For a thread safe random number generator look at RNGCryptoServiceProvider. From the docs:

Thread Safety

This type is thread safe.

查看更多
登录 后发表回答