0

program is asking 10 threads and launching it on a function which is printing random value , but all those threads are printing the same Random value .

My friends says that it is due to thread are using rand calculation at same CPU clock so that is why. Is he right

And if there is a solution for it ?

      private DateTime randomNum()
    {

         Random r = new Random();
        int rInt = r.Next();
    }

button_click1

         for (int i = 0; i < numofThreads; i++)
        {

            res[i] = delcall.BeginInvoke(null, null);
        }
        //int[] num = new int[numofThreads];
        for (int i = 0; i < numofThreads; i++) {
            DateTime dt = delcall.EndInvoke(res[i]);
            richTextBox1.AppendText(dt + "\n ");
        }
Shahan
  • 1
  • 2
  • 1
    This has been asked heaps of times, you need to put `private Random r = new Random();` outside the function, declaring it each time will make non-random. I'l l find the duplicate – Jeremy Thompson Sep 21 '17 at 05:24

1 Answers1

0

Don't create a new instance of Random every time. If multiple Random instances are created at the same time, their seed is the same. This means they all behave equal. Just use one Random instance multiple times. Therefore declare it outside of the method.

private readonly Random r = new Random();
private DateTime randomNum()
{   
    int rInt = r.Next();
}
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49