Amazon.com Widgets

Random.Next() always return 0??

This question came up on an internal list recently… Thought I’d share it with you…

 

Q: We have created a System.Random object and shared it among multithreads.  After calling m_random.Next() for awhile (eg. 1 day), it stops generate any random but only return zero. I realize that random is not thread safe.  I interpreted it as it might return the same random (in race condition) not that it will only return zero after sometime.

 

A: This comes up now and then.  As you note, and as we say in the docs, the class is not threadsafe.  That means anything can happen.  In this case it looks like the seed is getting corrupted.  Consider this fix:

 

class ThreadSafeRandom

{

    private static Random random = new Random();

 

    public static int Next()

    {

       lock (random)

       {

           return random.Next();

       }

    }

}

 

Also, if you are using this for any kind of security\privacy purposes, we suggest using the Random number generator in the System.Security namespace: RandomNumberGenerator.

 

Published 14 August 03 11:43 by BradA
Filed under:

Comments

# Eli Robillard's World of Blog. said on May 6, 2004 4:35 PM:
# you've been HAACKED said on October 9, 2006 11:50 PM:

re: Better CAPTCHA Through Encryption

# Eli Robillard's World of Blog. said on October 27, 2006 11:01 PM:

Random number generators written in code (or any deterministic algorithm) aren't really random. You

New Comments to this post are disabled

Search

This Blog

Syndication

Page view tracker