-2
class Run
{
      public delegate void PrintRandomEvent();
      public static event PrintRandomEvent print;

      public void run()
      {
             while(true)
            {
                  print();
            }
      }
}
class Print
{
      Run.print += new Run.PrintRandomEvent(this.print);
      public void print()
      {
             Random random = new Random();
             int n = random.Next(1,5000);
             Console.WriteLine(n);
      }
}

It keeps on printing the same random number in multiples before printing a new random number in multiples. I've tried adding Run.print -= new Run.PrintRandomEvent(this.print) but it does not do the trick just giving me null errors.

3 Answers3

0

Because this is how Random works, each time you create new instance very close in time to previous one you get the same random value.

Since it's connected to system clock

Just do not create new Random each time

Alexey Klipilin
  • 1,866
  • 13
  • 29
0

The Random class initializes itself by using the current date and time value of the system. The problem is that this clock is much slower than the CPU clock. Therefore, the CPU can yield several random values before the time clock ticks.

Make the random object static and always use this one and unique random object. At each successive call it will yield the next random value instead of different random objects always returning the first one depending on the system time.

class Print
{
    private static Random _random = new Random();

    public void print()
    {
         int n = _random.Next(1,5000);
         Console.WriteLine(n);
    }
}

static means that all Print objects share the same _random field.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
-2

Random is time based but maybe you can try something like this. But i didt test it.

class Print
{
      int seed = (new Random()).Next();
      Run.print += new Run.PrintRandomEvent(this.print);

      public void print()
      {
             Random random = new Random(seed++);
             int n = random.Next(1,5000);
             Console.WriteLine(n);
      }
}
Mustafa Çetin
  • 311
  • 2
  • 10