Random Number Generation in MVC Applications

What is the correct way to generate random numbers in an ASP.NET MVC application if I need exactly one number per request? According to MSDN, in order to obtain randomness of sufficient quality, it is necessary to create several numbers using one System.Random object created once. Since a new instance of the controller class is created for each request in MVC, I cannot use the private field initialized in the controller constructor for the Random object. So, in which part of the MVC application should I create and store a Random object? I currently store it in the static field of the controller class and lazily initializes it in the action method that uses it:

public class HomeController : Controller
{
    ...

    private static Random random;

    ...

    public ActionResult Download()
    {
        ...

        if (random == null)
            random = new Random();

        ...

    }
}

"" , , ? : , - , MVC, ? IIS IIS?

+5
3

Random , . , ; Random , . :

.

RandomGen2 Microsoft ParallelFX ( , ), ( ) .

public static class RandomGen2 
{ 
    private static Random _global = new Random(); 
    [ThreadStatic] 
    private static Random _local;

    public static int Next() 
    { 
        Random inst = _local; 
        if (inst == null) 
        { 
            int seed; 
            lock (_global) seed = _global.Next(); 
            _local = inst = new Random(seed); 
        } 
        return inst.Next(); 
    } 
}

:

var rand = RandomGen2.Next();

Random, , , ThreadSafeRandom, .

+10

- - - , (.. ) . , - , / , .

+2

HomeController, . , Random ( , ).

public class HomeController : Controller
{
    ...

    private static Random random;

    static HomeController()
    {
        random = new Random();
    }

    ...

    public ActionResult Download()
    {
        ...

        //use random - its already created.


        ...

    }
}
+1

All Articles