c# - why my HttpContext.Application variable cannot be access through different Actions in ASP.NET MVC -
i created aspnet mvc program, , want variables can shared every visitor.
typed code global.asax:
protected void application_start(){ smequeue[] smetime = new smequeue[10]; application["waittime"] = smetime; ...
however, can't modify array in application. can read in every actions in contyoller this:
smequeue[] arr = system.web.httpcontext.current.application["waittime"] smequeue[];
but after change values in array in action, in other actions still original array assigned in global.asax. modification cannot pass other actions.
why , can do?
found there many similar questions on stackoverflow, sadly answers not work mine.
more codes:
i edit variable in action:
public actionresult create() { smequeue[] arr = system.web.httpcontext.current.application["waittime"] smequeue[]; arr[0] = new smequeue("hello");//elements of arr null before
then access action:
public actionresult tryconnect() { smequeue[] arr = system.web.httpcontext.current.application["waittime"] smequeue[]; request.write(arr[0].tostring());//it' null.
if assign value variable in application_start(), can access value anywhere (any actions). after modify value in action, read in other actions still value assigned in application_start().
you first need understand application objects created more once. therefore different requests may using different application objects. makes sense 1 action reading start values rather modified values because being handled different application objects.
disadvantages of application state:
application scope scope of application state can disadvantage. variables stored in application state global particular process application running in, , each application process can have different values. therefore, cannot rely on application state store unique values or update global counters in web-garden , web-farm server configurations.
asp.net state management recommendations
a classic example encounter iis winding down application due inactivity default 20 minutes believe. when next request hits server new worker process spun new application object , therefore state.
so if need maintain state beyond single session , application, need form of state persistence, typically database, write/read through too.
i using:
- httpcontext short lived per user per request storage
- cookies long lived per user multi request storage
- cache long lived multi user, multi request data
- application state global lookup data doesn't (daily, weekly, monthly) bearing in mind you'll have manage wind down, spin old new data.
- and reaching out db or other efficient read/write medium type of thing seem trying / page counters etc.
to test of put breakpoint on application_start code , see how many times gets hit, every time that's new application object in play.... plus looking @ threads in debug windows of vs can informative.
Comments
Post a Comment