c# - Using static variables instead of Application state in ASP.NET -
i plane use static variables instead of application state in asp.net , wondering if correct approach:
[global.asax.cs] ... public class global : system.web.httpapplication { void application_start(object sender, eventargs e) { // code runs on application startup } ... private static dictionary<string, object> cacheitems = new dictionary<string, object>(); private static object locker = new object(); public static dictionary<string, object> cacheitems { { lock (locker) { return cacheitems; } } set { lock (locker) { cacheitems = value; } } } public static void removecacheitem(string key) { cacheitems.remove(key); } ... }
as can see use automatically created global.asax (and code behind) file. i've added static variables , methods. can use them after in manner:
[some .cs file] foreach(keyvaluepair<string, object> dictitem in global.cacheitems) { ...
is right way or should create new class instead of existing global? if should create new class how can , where?
what microsoft says
asp.net includes application state compatibility classic asp easier migrate existing applications asp.net. recommended store data in static members of application class instead of in application object. increases performance because can access static variable faster can access item in application dictionary.
reference : http://support.microsoft.com/default.aspx?scid=kb;en-us;q312607
my expirience
the main different between static variables , application state, application state same across threads , pools, static same per pool.
after new tests see application state variables same static variables, , reference static variable on application, , exist compatibility reasons microsoft says
if have 4 pools running site (web garden) have 4 sets of different static memory.
your code
about code, have bug way try access dictionarry data, , going have errors in real web. part of code lock variable of full dictionary not lock change going make when use it.
// not enough manipulate data ! public static dictionary<string, object> cacheitems { get{ lock (locker){return cacheitems; } } set{ lock (locker){cacheitems = value;} } }
the correct approach lock actions of add/remove until done, example.
private static dictionary<string, object> cacheitems = new dictionary<string, object>(); private static object locker = new object(); public dictionary<string, object> cacheitems { get{ return cacheitems; } set{ cacheitems = value;} } somefunction() { ... lock(locker) { cacheitems["variablename"] = someobject; } ... }
from other hand when manipulate data on application state need use global lock of application.lock();
, application.unlock();
example
application.lock(); application["pagerequestcount"] = ((int)application["pagerequestcount"])+1; application.unlock();
to close result:
avoid application state , use static variables on code.
Comments
Post a Comment