How do static properties work in an asp.net environment?

10,527

Solution 1

Statics are unique to the application domain, all users of that application domain will share the same value for each static property. When you see the word static, think "there will only be one instance of this." How long that instance lasts is a separate question, but the short answer is that it is variable.

If you want to store values specific to the user look into Session State.

Solution 2

In addition to Bob's answer, there is this exception of course:

public static object Item {
    get { return HttpContext.Current.Session["some_key"]; }
}

Solution 3

Static fields and properties are shared across all instances of a class. All of your users will end up sharing the same value.

The value will be there until the ASP.NET worker process recycles itself (which happens periodically).

Solution 4

No, it's nothing special just because it's asp.net. ASP.NET itself is just a regular .NET assembly collection. If you want to save things per sessions then you should use the session state. If not, be careful since there are many threads that can access your static data. You should read and learn how threads, locks and race conditions work together.

Share:
10,527

Related videos on Youtube

asawyer
Author by

asawyer

Want to tip/donate? http://www.unicef.org/

Updated on March 04, 2020

Comments

  • asawyer
    asawyer about 4 years

    If I had a class with a static property that is set when a user loads a particular page, is that static value unique to that users session?

    In other words, if a second user then loads the page and sets the static property, will each user have a distinct value, or will both use the second users value?

    • Josh McKearin
      Josh McKearin almost 12 years
      Have you read the documentation or tried it out yourself?
  • Dan Lugg
    Dan Lugg about 11 years
    +1 -- I got bit once, having foolishly removed assignment logic against a static property. The value stuck around long enough for me to nearly forget about it, and have a hay-day unwinding the mess when the pool did in fact recycle. Moral of the story: be careful with statics, as in any case, but especially in ASP.NET.
  • Joe
    Joe over 10 years
    And many others: HttpContext.Current itself for example, and DateTime.Now. Static fields are shared (unless decorated with the ThreadStatic attribute), but static properties can do whatever they want.