Why does my ASP.Net static function's “context” crossover between user sessions?

后端 未结 5 1062
醉酒成梦
醉酒成梦 2020-12-16 03:58

I think I need some help understanding how static objects persist in an ASP.Net application. I have this scenario:

someFile.cs in a class library:

p         


        
相关标签:
5条回答
  • 2020-12-16 04:25

    Static data is shared among the entire application domain of your webapp. In short, it's shared among all the threads serving requests in your webapp, it's not bound to a session/thread/user in any way but to the webapp as a whole.(unlike e.g. php where each request lives in its own isolated environment bar a few knobs provided - such as the session variable.)

    0 讨论(0)
  • 2020-12-16 04:32

    One solution you might consider is using [ThreadStatic].

    http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx

    It will make your statics per thread. There are cavaets however so you should test.

    0 讨论(0)
  • 2020-12-16 04:34

    If you want the data to persist only for the current request, use HttpContext.Items: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx

    If you want the data to persist for the current user's session (assuming you have session state enabled), use HttpContext.Session: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.session.aspx

    0 讨论(0)
  • 2020-12-16 04:35

    I won't try to improve on the other answers' explanations of static members, but do want to point out another way to code around your immediate problem.

    As a solution, you could make an instance-oriented version of your class A, store it in a page-level variable, and pass it to Q's constructor on page load:

    public class MyPage: Page {
        private A2 _a2;
    
        // I've modified A2's constructor here to accept the function
        protected Page_Init() { this._a2 = new A2(MyFunc); }
    
        protected Page_Load() { 
            Q myQ = new Q(this._a2); 
            // etc..
        }
    }
    

    In fact, if there's no pressing need to declare A2 earlier, you could just instantiate it when you create your instance of Q in Page_Load.

    Edit: to answer the question you raised in other comments, the reason the variables are being shared is that the requests are sharing the same delegate, which has only a single copy of its variables. See Jon Skeet's The Beauty of Closures for more details.

    0 讨论(0)
  • 2020-12-16 04:37

    Each request to an asp.net site comes in and is processed on it's own thread. But each of those threads belong to the same application. That means anything you mark as static is shared across all requests, and therefore also all sessions and users.

    In this case, the MyFunc function that's part of your page class is copied over top of the static Func member in A with every page_init, and so every time any user does a page_init, he's replacing the A.Func used by all requests.

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