Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just protect the random number generator with a lock. Unless you're making hundreds of thousands of calls per second to it, it's going to be plenty fast enough.</p> <pre><code>public class MyRandomObject { private readonly Random _rnd = new Random(); public int Next() { lock (_rnd) { return _rnd.Next(); } } } </code></pre> <p>Before you say, "locks are too slow," note that I tested this on an old 2.4 GHz quad core. It took approximately 70 nanoseconds to get a random number when the lock isn't contended. Lock contention can kill performance, but you'd need lots of requests.</p> <p>In a Web app, you'd want to initialize one of those in <code>Application_Start</code>, and make that singleton available to the rest of your application.</p> <p>There are faster ways, but they're more difficult to implement. One way would be to pre-generate millions of random numbers (call <code>Random.NextBytes</code>) and store them in a buffer. Protect that with a reader/writer lock. When the number of values remaining reaches some threshold, the thread grabs the writer lock, preventing all other access until it refills the buffer. This is probably the way you'd want to go if you're using some other source of random numbers. For example the <code>RNGCryptoServiceProvider.GetBytes</code> method (<a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.getbytes.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.getbytes.aspx</a>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload