Note that there are some explanatory texts on larger screens.

plurals
  1. POProperly Seeding Random numbers in Class Library called from ASP.Net Web Page
    primarykey
    data
    text
    <p>I'm experiencing a problem with my random number generator in a class library returning the same value repeatedly. It returns the same value b/c it is repeatedly initialized with the default constructor - for example: <br /></p> <pre><code>public static T GetRandomValue&lt;T&gt;(T[] array) { int ndx = new Random().Next(array.Length); return array[ndx]; } </code></pre> <p>This is called repeatedly from another method before the system clock can change, so it is initialized with the same random seed, giving the same value. (see <a href="https://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c">SO article for apparently malfunctioning random number generator</a>) It is used to select a random format string for some text generation algorithms. Because it is called in rapid sequence every time my different bits of text generates with a homogeneous formatting string, which is undesirable for the application. <br /> <br /> It is typically called from an asp.net webpage, and I'm wondering what the best approach is to produce a random sequence, without creating performance issues for the pages that call the method repeatedly.</p> <p>A web page calls the library method, which calls the random number. I am wondering if i can use this approach for a static number generator instead. Are there performance issues associated with calling a static method like this from a webpage?</p> <pre><code>public class Utility { public static Random random = new Random(); public static T GetRandomValue&lt;T&gt;(T[] array) { int ndx = random.Next(array.Length); return array[ndx]; } } </code></pre> <p>A lock on "random" and "ndx" may be needed too. Is there a better practice in general for handling this type of seeding in a class library?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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