does aspx provide special treatment for c# static variables

后端 未结 1 341
终归单人心
终归单人心 2020-12-21 09:28

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

相关标签:
1条回答
  • 2020-12-21 10:11

    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.

    Example

    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 {
         get;
         set;
    }
    
    // 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{
        get{
            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{
        get{
            // 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.

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