System default permission for system generator?

I have several processes in which I use the default constructor for System.Random to generate random numbers. I read about it on MSDN, but it does not talk about the specific resolution of the system clock that it uses, for example, does System.Random get the semantic time of the system in milliseconds or seconds? Is it possible to use the default constructor for several processes to get random values โ€‹โ€‹between them?

Greetings

+4
source share
4 answers

it uses Environment.TickCount , you can check it in Reflector. But the point is to get a unique seed, so you can use the arithmetic operation on this value using ProcessID. as:

 Random(Environment.TickCount + System.Diagnostics.Process.GetCurrentProcess().Id); 

and etc.

+3
source

Seed is in milliseconds ranging from 10 milliseconds to 16 milliseconds. But the most important thing to remember is that you should always use the same instance of Random if you can generate different "random" values. If you always create a new instance in a narrow loop, you get the same value many times.

So it's safe to use the default constructor if you use the same instance anyway. If you do not need them in different streams, you can use this helper class from Jon Skeet (from here ):

 public static class RandomHelper { private static int seedCounter = new Random().Next(); [ThreadStatic] private static Random rng; public static Random Instance { get { if (rng == null) { int seed = Interlocked.Increment(ref seedCounter); rng = new Random(seed); } return rng; } } } 
+3
source

If you use different processes, consider using a process identifier to create a single instance of Random for each process.

 private static readonly Random _theSingleRandom = new Random(Process.GetCurrentProcess().Id); 
+2
source

System.Random uses TickCount as its seed. The MSDN documentation at http://msdn.microsoft.com/en-us/library/windows/desktop/ms724408(v=vs.85).aspx states

The resolution is [...] limited by the resolution of the system timer, which usually ranges from 10 milliseconds to 16 milliseconds.

Thus, between 2 different TickCount values, there are 10 to 16 milliseconds.

0
source

Source: https://habr.com/ru/post/1444368/


All Articles