If I need a number for every request, then what is the correct way of generating a random number in the ASP.NET MVC application is? According to MSDN, to achieve randomness of sufficient quality, it is necessary to produce many numbers using a single system. Random object was created once, since a new instance of a controller class has been created for each request in MVC, so I can not use the private field started in the controller's constructor for random objects. So should I make some parts of the MCC app a random object and store it? At present, I store it in a fixed area of the controller class and starts it in a slow process method which uses it:
Public Sector Home Controller: Controller. Private static random random; ... public performance download () {... if (random == null) random = new Random (); ...}} Since the "random" field can be accessed by several examples of controller class, is it possible that its value get corrupted if two instances begin simultaneously? Try to do it? And another question: I know that the lifetime of the static is the life of the application, but what is this in the case of an MVC app? Is Iis shutting down from IIS startup?
Ideally you'll be random
for more than the lifetime of a page . Do this by placing it in a fixed variable not ; random
class is not thread-safe and will result in problems from
My favorite approach is the wrapper class from the Microsoft Parallel Fx team (which really knows What are they doing with threading) that uses an example thread per thread for fresh-free and thread-safe random numbers.
public static class RandomGen2 {Private static random = global = new random (); [ThreadStatic] Private static random _local; Public stable int next () {random inst = _local; If (inst == faucet) {int seeds; Lock (_Global) Seed = _global.Next (); _local = inst = new random (seed); } Return inst.ext (); }}
which you can call only by:
var rand = RandomGen2.Next ();
You may need to add additional method to reach you other random
methods, and give me a better name such as ThreadSafeRandom
, but it reflects the principle.
Comments
Post a Comment