¿aspx proporciona un tratamiento especial para las variables estáticas c#?

in a .net web app is there something special about .aspx pages and the c# code behind pages that changes the behaviour of static variables.

i have a large number of application pages that were developed elsewhere and there is a common pattern running thru them where what i think should be an instance variable is declared as a static variable.

a more detailed statement of the question would be: if i have two web sessions a and b running on the same iis server in the same application pool, if a accesses the page in question and sets static variable x to value1 and then b accesses the same page and sets static variable x to value 2, my understanding is that value1 has been replaced by value 2. my dilemma is that this pattern is used repeatedly in the code, at a high level the code appears to work. the conclusion is that it is either luck (timing as in session a has abandoned the need for the variable before session b hits it) or there is something else going on.

i am open to suggestions whether this is a c# nuance or a developer bug.

preguntado el 31 de julio de 12 a las 11:07

1 Respuestas

Static properties/fields are fine in web applications as long as they are used for shared data which can acceptably disappear at any time, such as when an app pool recycles.

That said, their values are indeed shared inside an ASP.Net application unless they have a segregated backing mechanism, like Session.


public static int UserId = 10; // BAD! everyone gets/sets this field's value

// BAD! everyone gets/sets this property's implicit backing value
public static int UserId {

// This case is fine; just a shortcut to avoid instantiating an object.
// The backing value is segregated by other means, in this case, Session.
public static int UserId{
        return (int)HttpContext.Current.Session["UserId"];

// While I would question doing work inside a property getter, the fact that 
// it is  static won't cause an issue; every call retrieves data from a 
// database, not from a single memory location.
public static int UserId{
        // return some value from database

You may not see an issue until traffic is significant. Suppose a page retrieves a value, puts it in a static variable, uses it once, then completes execution. If the page executes quickly, there is only a very small (but dangerous!) window of overlap that you may not see unless the timing is right and/or traffic is high enough.

This can lead to hard-to-diagnose bugs, because they are dependent on timing and you probably will not see them when testing by yourself on your local machine.

Respondido 31 Jul 12, 12:07

thats what i thought, and i appreciate the verification. looks like i got a whole bunch of code cleanup to do :) - dan-

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.