I’ve always wondered how you can access the correct state of the current http context via a static method:
HttpContext.Current.Session["foo"] = "bar";
In any other program, anywhere else, my initial assumption about working with a static accessor like this is that changing it will change it across all threads. Similarly, another thread running my change it on me while I am trying to use it.
But HttpContext.Current does not behave like this. It provides the appropriate state for the given request, even through the static accessor. How is this?
Basically, HttpContext has a static property getter named Current. In that property getter is code that determines the correct HttpContext object to return.** After that, you’re using instance methods. Your snippet is equivalent to:
Part of how it does it isn’t really magic – the ASP.Net runtime sets HttpContext.Current for each request to a new instance of HttpContext. That setter stores the instance in thread static storage***. The getter then pulls the instance out of that storage for the current thread.
The key thing to note is that a static property or method isn’t just global fields – it can use things like the current thread to alter what it does or what it returns.
**Actually, HttpContext.Current delegates to ContextBase, which delegates to CallContext, which ends up using methods on Thread, but the concept is the same.
***Actually, the runtime does a bit more to handle thread switching during a request.