Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same value is returned from async method [duplicate]

I have stared myself blind on this now, so please help.

When I call this method twice, inside a loop, it returns the same values. Why ?

public async Task<int> RollDice() {
    var rnd = new Random();
    var selected = 0;

    await Task.Run(() => {
        selected = rnd.Next(1, 6);
        });

    return selected;
}
like image 620
danielovich Avatar asked Jun 18 '26 15:06

danielovich


1 Answers

You have to initialize the Random object outside of the method to prevent it from being initialized over and over again with the same seed and therefore returning the same values.

It is important to notice, as LukeH correctly adds in the comments, that the System.Random class is not thread safe and should not be shared among tasks in separate threads.

like image 62
John Willemse Avatar answered Jun 21 '26 06:06

John Willemse