Your father
Your father

Reputation: 107

Static properties across different ASP.NET requests

If I create a static property MyLanguage and one request sets its value to 1, while at the same time another thread sets it to 2 - what will be the final value of MyLanguage?

Does the single MyLanguge property gets shared across ASP.NET sessions?

Upvotes: 3

Views: 2936

Answers (3)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

A static property/field is shared across the app domain. So all your sessions should see the same value.

The only exception is when you use the ThreadStatic attribute on a static field, in which case each thread will see its own value. e.g.

[ThreadStatic]
static int counter = 0; // each thread sees a different static counter.

Upvotes: 9

Anant Dabhi
Anant Dabhi

Reputation: 11114

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: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

It would be 2. Static fields, properties are shared between objects.So Latest set values will be updates for all the instances.

From MSDN

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For more information

Upvotes: 2

Related Questions