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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With