开发者

Use of static objects in asp.net

开发者 https://www.devze.com 2022-12-19 19:35 出处:网络
I am using the followign object in my asp.net page 开发者_如何学Goprivate static Dictionary<string, List<Guid>> OpenNodes = new Dictionary<string,List<Guid>>();

I am using the followign object in my asp.net page

开发者_如何学Goprivate static Dictionary<string, List<Guid>> OpenNodes = new Dictionary<string,    List<Guid>>();  
//Page start
if(!OpenNodes.ContainsKey(Session.SessionID))  
{  
    List<Guid> list = new List<Guid>();  
    OpenNodes.Add(Session.SessionID, list);  
}

//User clicked on a node
Guid id = new Guid(e.Node.Value);  
tmpList = OpenNodes[Session.SessionID];  
tmpList.Add(id);  
OpenNodes[Session.SessionID] = tmpList;  

Is it agood practive or is there a similar 'better' way to achieve the same?


You should not replace Session with static fields. Session is much more flexible and less error-prone. You can easily make it work in Web farms (you can't do that with static fields). You can consider replacing some Application variables with static fields. It's important to know that static fields don't provide any thread safety mechanism out of the box and you should manually control (lock) them appropriately.


A web server is multi threaded. You need to synchronize access to shared/static objects


In this case, you can just use the Session state. I see no pro's in using the pattern you propose here.

If you really need to mimic some static field. You should use the Application state.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号