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

元气小坏坏 提交于 2019-11-30 09:35:41

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.

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.

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!