0

I am trying to pick a random Element from an Array for every time my Parallel Foreach-loop executes.

But for some reason, it always prints out the same string. I also tried to use the return of a function, but this also doesn't work.

Here is my Code:

Parallel.ForEach(stringArray, element =>
{
 Colorful.Console.WriteLine(pickElement(element));
 Colorful.Console.WriteLine(pickElement(element));
 Colorful.Console.WriteLine(pickElement(element));
});

private static string pickElement(String[] array)
{
 Random random = new Random();
 return array[random.Next(0, array.Length)];
}

Solved, thanks to everyone who answered! ^^

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Error 404
  • 1
  • 2
  • 2
    Don't create a `Random` instance in a tight loop -- there are loads of dups on SO about this. Your situation is further compounded by the fact that `Random` isn't thread-safe, so you can't use a single instance across all threads. A simple solution would be to use a single `Random` instance and protect it with a lock, but lock contention might be a major issue, in which case you'll need to create a `Random` instance per thread – canton7 Apr 14 '21 at 11:39
  • @canton7 Add a linebreak or two and you have an answer. – nvoigt Apr 14 '21 at 11:43
  • 1
    Instead of calling `Random` inside the loop, produce a sequence of random values before you even start the loop. Most random number generators depend on previous state so they are *not* thread-safe. The cryptographic RNGs are, and actually produce better random sequences *but* these can't be replicated. – Panagiotis Kanavos Apr 14 '21 at 11:44
  • Is it ok to have repeated numbers printed? Then simply move `new Random()` out of the loop. Do you want to print all elements in the random order? Then you need a determinitistic random or just shuffle items in the collection before running the loop. – Sinatr Apr 14 '21 at 11:51
  • So `stringArray` is an array of string arrays? – 500 - Internal Server Error Apr 14 '21 at 11:57
  • You can pass the iteration number as the seed to the `Random` constructor. This will avoid generating identical sequences although after a time they'll overlap. The sequence generated by a deterministic RNG algorithm is the same every time. The seed specifies the starting point in that sequence. Even small differences result in very different numbers. Since the sequence is the same though, at some point Worker #1 will start producing the same values Worker #2 produced earlier – Panagiotis Kanavos Apr 14 '21 at 12:04
  • @nvoigt Then it'll get downvoted as this question is a dup of all the other hundreds of Random misuse questions. – canton7 Apr 14 '21 at 12:32

0 Answers0