C # Random.Next suddenly stops returning random values

Possible duplicate:
System.Random continues to return the same value

I am refactoring and expanding a small C # -based model to help some biology professors predict the spread of the disease. Each year of simulation, each individual agent randomly moves to a neighboring node population, possibly spreading the disease. I'm new to C #, but I read about potential issues with Random.Next returning the same value if reinitialized with the same system time. To avoid this, I created a static instance referenced for each new random value.

Features:

In my efforts to expand the model, I modified it to calculate the "path" information for each node population in parallel. When testing the model, I noticed that in the new version the disease would not have spread in the first year. A further request narrowed the problem down to moving between nodes. After the first year, all agents remained motionless. I examined the function responsible for driving them, and found that it works by creating a list of all the nearest nodes, generating a random number <= the number of elements in the list and moving to listOfNearbyNodes [myRandomNumber].

Problem:

. , , , , . "" 0. , , node, 0. node , .

, , , . , , , Random.Next() 0.

- , ? !

+5
4

, Random . - .

:

  • Random (ThreadStatic )
  • Random, - .

, , , , . - ...

+18

, Random ( ) - , , , .

, Random, ThreadStatic, :

[ThreadStatic]
private static Random m_Random;  // don't attempt to initialize this here...

public void YourThreadStartMethod()
{
    // initialize each random instance as each thread starts...
    m_Random = new Random();
}

.NET 4.0, ThreadLocal<T>, .

+5

Random . , , :

class ThreadSafeRandom 
{ 
    private static Random random = new Random(); 

    public static int Next() 
    { 
       lock (random) 
       { 
           return random.Next(); 
       } 
    } 
}

RNGCryptoServiceProvider, , .

+2

All Articles