mercredi 23 février 2022

How to implement a thread-safe random

Trying to find and understand the best approach to implement a thread-safe number generator in .NET Core 2.x or higher

First Iv'e found this - https://web.archive.org/web/20160326010328/http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx

After reading through it seems to me like there are couple of "good" ways -

  1. ThreadStatic Random instance, with a global random instance to generate seeds
  2. ThreadStatic Random instance, with a global RNGCryptoServiceProvider to generate seeds

Where basically you choose the latter if a strong cryptographically random is a requirement.

After some additional research I found out that since .NET Core 2.x System.Random class was revised, therefore the default seed generation which is no longer primary dependent on the system timer. (https://blogs.siliconorchid.com/post/coding-inspiration/randomness-in-dotnet)

Questions -

  1. How is this affect the implementation of a thread-safe random class?
  2. Initially having a global static Random instance as a seed generator with a lock resulted with about 16ms timespan of same results per thread due to OS limitation, is this no longer the case? do I even need a global seed generator?
  3. Knowing all of this, when should I use a cryptographic class (RandomNumberGenerator) instead of System.Random ?



Aucun commentaire:

Enregistrer un commentaire