asawyer
asawyer

Reputation: 17808

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

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?

Upvotes: 25

Views: 11677

Answers (4)

Protector one
Protector one

Reputation: 7271

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

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

Upvotes: 5

Erv Walter
Erv Walter

Reputation: 13788

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).

Upvotes: 4

Onkelborg
Onkelborg

Reputation: 4007

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.

Upvotes: 1

Bob
Bob

Reputation: 99784

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.

Upvotes: 22

Related Questions