Random object not in C #

I am working on an algorithm for generating smooth terrain in C # and am using XNA to display data.

I do this so that it creates a new point halfway between each point to iterate at a random height between them. This works fine, and I set it so that in the second iteration it selects a random point, like in slide two, instead of trying to create a new point between points located on the same axis.

What happens is that the loop uses the same random value from the previous iteration: http://i.stack.imgur.com/UmWr7.png

This is not ideal, obviously, since it is not the correct random generation.

If I use Thread.Sleep(20) after each point generation, it works correctly: http://i.stack.imgur.com/KziOg.png

I do not want to use the Sleep workaround, if possible, as it is very slow, and I would like to use it in real time. I'm pretty sure this has something to do with the C # garbage collector.

Here is my recipient point code

 Random r = new Random(); int x = (p1.X + p2.X) / 2; int y; if (!initial) y = r.Next(Math.Min(p1.Y, p2.Y), Math.Max(p1.Y, p2.Y)); else y = r.Next(Math.Min(p1.Y, p2.Y) - Game1.screenHeight / 2, Math.Max(p1.Y, p2.Y) + Game1.screenHeight / 2); return new Point(x, y); 

Is garbage collection part of the problem?

Any suggestions or solutions to resolve this issue.

+6
source share
2 answers

You are probably creating a new random object in a loop.

 for (/* ... */) { int x = new Random().Next(); // Don't do this! // ... } 

Try to create only one instance of Random at program startup, then reuse it. If you have multiple threads, you can use one random object for each thread.

+10
source

It looks like you are probably creating a new instance of Random at each iteration 1 . It will take its seed from the current time - so without sleep you will again get the same value; with sleep, you end up with another seed.

The answer is to reuse one instance of Random in your entire program, but taking into account the fact that Random not thread safe. If all your work is done in the user interface thread, you will be fine - but otherwise you can use one of the approaches that I gave in the article about Random (more about this issue).


1 And yes, now that you have posted the code that really takes place.

+6
source

Source: https://habr.com/ru/post/900356/


All Articles