System.Random and random sequences #math-random

This post first appeared on the Forse company blog.

Actually, this is .NET 101. Probably everyone who has worked with the Random class already knows this. However, last week we encountered a Heisenbug in one of our feature, and this blog post is just a reminder of how the Random class works.

The bug: Our system is generating sample data files. In this specific case, we were generating thousands of sample files. Each file contains some metadata and a time series. It turned out that all these files had the identical same time series values, but correct metadata. When we debugged, everything looked good; all sample files had different time series.

It turned out that we created a new instance of the Random class for each sample generation. What people may not know, is that two different random instances will produce the exact same random sequence if the instances are using the same seed. When not specifying the seed value, the system clock will be used to generate the seed. So, instantiating two random generators in close succession will result in two identical random sequences. You can read more about this in the documentation.

Here is a demo of the described behavior.

The code:

The output:


And now, sleeping for 1ms between the random generators (line 12):

Which is enough to generate different sequences:


So, lastly, if you want to have true random sequences, within your scope of work, you need to always use the same random instance. A static instance would have solved our problem, but an even quicker fix for us was to just use a new Guid’s hashcode as a seed every time.


Thanks for reading!