Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Don't create a new instance of <code>Random</code> on each iteration - that's going to seed each instance with the current time in milliseconds, which obviously isn't likely to change between iterations.</p> <p>Create a single instance of <code>Random</code>, and pass it into the method. I'd also advise you not to concatenate strings like that in a loop, or even to create that many strings. Additionally, if you use <code>Random.Next(int, int)</code> to make your life a lot easier.</p> <p>Try this:</p> <pre><code>public char GenerateChar(Random rng) { // 'Z' + 1 because the range is exclusive return (char) (rng.Next('A', 'Z' + 1)); } public string GenerateString(Random rng, int length) { char[] letters = new char[length]; for (int i = 0; i &lt; length; i++) { letters[i] = GenerateChar(rng); } return new string(letters); } private static readonly Random SingleRandom = new Random(); public string GenerateStringNotThreadSafe(int length) { return GenerateString(SingleRandom, length); } </code></pre> <p>Now it's worth being aware that <code>Random</code> isn't thread-safe, so if you've got multiple threads you shouldn't just have a single instance of <code>Random</code> in a static variable without locking. There are various ways around this - either create a subclass of <code>Random</code> which <em>is</em> thread-safe, or a set of static methods which do the same thing, or use thread-local variables to have one instance per thread.</p> <p>I have a <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/staticrandom.html" rel="noreferrer"><code>StaticRandom</code> class</a> as part of <a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> but these days I'm leaning towards the thread-local version and passing it down the chain where appropriate. One day I'll add that as another option to MiscUtil...</p>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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