What is better: Static variable V.S. Asp.NET Application Session?

前端 未结 4 1742
难免孤独
难免孤独 2020-12-17 22:41

Say you want to share some resource, like a class or a variable across all threads/sessions within a ASP.NET web application. What is better?

1) A static variable h

相关标签:
4条回答
  • 2020-12-17 22:51

    This is a common scenario in which you are going through multiple pages and collecting data. I would use a Session object for this scenario. Static variables should be used when the complete application is in need for the same object.

    If the value you want to hold is dependent on the user then use Session.

    0 讨论(0)
  • 2020-12-17 22:52

    If you only have one of those, there is little difference.

    If you have several, you should use static variables rather than Application variables. The Application.Lock method will lock all Application variables, while you can use separate syncronisition identifiers for your static variables, so that each lock only affects the code that accesses that specific variable.

    0 讨论(0)
  • 2020-12-17 22:59

    Static Members will offer better performance, but the down-side is they are not thread safe:

    It is recommended that you store data in static members of the application class instead of in the Application object. This increases performance because you can access a static variable faster than you can access an item in the Application dictionary.

    From: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

    and:

    http://weblogs.asp.net/plip/archive/2003/12/01/40526.aspx

    0 讨论(0)
  • 2020-12-17 23:11

    That's true session variables should only be used for if you want to store the value for the whole session, but in the case you want the variables to be intitialized and to be used in between the forms and if changed in betwwen should be available through the whole application for the same object must use static variables.

    0 讨论(0)
提交回复
热议问题