matthewlynch.net Musings on programming, electronics, and other such things.

5Jan/110

Good seed for Random()

I often run in to a scenario where I need an easy way to generate random numbers. In most of these case, I don't care whether the numbers are entirely random, or just psuedo-random; all I want are numbers that have a decent level of variation.

In .NET, System.Random is great for this, but there is one issue: the default seed is time based.

In a lot of cases, the default seed is fine - because it is based on a high precision clock - but when you are working with multiple threads, it becomes problematic.

There are many (many, many) solutions to this, but today I stumbled across one that is simple, and reasonably elegant:

Random random = new Random(Guid.NewGuid().GetHashCode());

Because of the astronomically low chances of a GUID collision, this method of seeding as good as guarantees that each of your threads will be operating with a different seed.

The GUID needs to be hashed because the seed must be 32-bit.

I should note that you should not use this for anything relating to security. If you need a random number for security purposes, use a secure random number generator.

Filed under: .NET, C# Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.