简体   繁体   中英

Same value is returned from async method

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.

You're using two instances of the Random class. Using the parameterless constructor , the the random number generator is seeded using a system clock based value.

This means that if you're creating two Random instances shortly after each other, they will be initialized using the same value, because the system clock has a finite resolution. Having the same seed means that these two instances will produce the same sequence of results.

Some Googling revealed that using Random cross-thread can cause it to break and return an endless sequence of zeros, so if you have to multi-thread this particular part of the code, you may want to look at this article on how to create a single thread safe version of the Random class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM