Tell this line:
int seed = (int)DateTime.Now.Ticks;
If you run this line twice in a row, what do you think the values will be?
For example:
int seed1 = (int)DateTime.Now.Ticks; int seed2 = (int)DateTime.Now.Ticks;
See my article an article on randomness for a solution and more information.
EDIT: here's a quick and dirty example of thread insecurity causing problems:
using System.Collections.Generic; using System.Threading; class Program { const int Iterations = 1000000; static readonly Random rng = new Random(); static void Main(string[] args) { List<Thread> threads = new List<Thread>(); for (int i = 0; i < 8; i++) { Thread t = new Thread(ExerciseRandom); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); } static void ExerciseRandom() { for (int i = 0; i < Iterations; i++) { rng.Next(); } } }
The output in my field is:
0 0 0
Jon skeet
source share