c# - Why Random().Next(min, max) always generate same minimum value in ASP.NET MVC app -
i trying understand seems quite mystical @ point after hour analysis. please bear detailed explanation.
i got function in asp.net mvc4 application.
private string generatedownloadcode(int id, int organizationid) { const int downloadcodeminvalue = 10000000; const int downloadcodemaxvalue = 20000000; int number = new random().next(downloadcodeminvalue, downloadcodemaxvalue); return string.format("{0}-{1}-{2}", id, organizationid, number); }
the function used generate random number download code. noticed number
value equal downloadcodeminvalue
.
i checked msdn , dig implementation of next method in framework code looks like:
long range = (long)maxvalue-minvalue; if( range <= (long)int32.maxvalue) { return ((int)(sample() * range) + minvalue); } else { return (int)((long)(getsampleforlargerange() * range) + minvalue); }
sample() method can return value 0.0 1.0 , think in case returning 0.0 causing method return minvalue. ok "legal value random number".
i can live until pick method , copied linqpad generating random number consistently.
q1: why same method return expected random number in linqpad?
i read questions around (very close problem, mvc specific not consider case) explains random
class behavior , offer solutions.
the above links assume code invoked in close loop or shorter time period, in case method called @ least minute difference if not hour.
i not have problem getting same number not want fix code, inability , curiosity understand why not working in mvc app (each request served in new thread) making me reach experts here.
q2: reason the method not return random number in mvc app?
update:
context method - method used generate new random long (>= 12 char) enough number each new organization added. hence each call minutes delayed.
update 2:
the method called method addorganizationuser
exist in different library (business or service). service method invoked controller action
public actionresult createuser(organizationuserviewmodel ouser) { organizationuserservice.addorganizationuser(organizationuserdomainmodel, loggedinuser.id); }
i think u calling multi-threaded environment? random not thread safe.
here number of ways implement thread safe random. http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
hope helps
edit: creating new random each random number bad practice.
Comments
Post a Comment