问题
i have serialization problem with session(as i described here) so i used static Dictionary instead of session asp.net mvc
public static Dictionary<string, object> FlightDict;
FlightDict.Add("I_ShoppingClient", client);
in this case user will override their values?are there any problem with that because they says with static variable users data can be overrided
回答1:
Yes, you can change the static variables in the site, But You need to use this to change the data but that is not enough you need to lock this data until you have done.
public static Dictionary<string, object> CacheItems
{
get{ return cacheItems; }
set{ cacheItems= value; }
}
How to Lock?
The approach you need to use to lock all actions of add or remove until you done is:
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;}
}
YourFunction()
{
lock(locker)
{
CacheItems["VariableName"] = SomeObject;
}
}
for manipulating the data on application state you need to use the global lock of it Application.Lock();
and Application.UnLock();
. i.e
Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1;
Application.UnLock();
Last: Avoid Application State and use the Static Variable to Manage the Data across the Application for Faster Performance
Note: you can add one lock at the time only so remove it before you are trying to change it
Keep in Mind : The static variables will be shared between requests. Moreover they will be initialized when application starts, so if the AppDomain, thus application gets restarted, their values will be reinitialized.
来源:https://stackoverflow.com/questions/25283877/using-static-dictionary-instead-of-session-asp-net-mvc