using static Dictionary instead of session asp.net mvc

白昼怎懂夜的黑 提交于 2019-12-25 08:48:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!