views:

182

answers:

2

So I'm left wondering how exactly asp.net is able to scope a static property, when (to my knowledge) asp.net is multi-threaded.

  • One theory goes that the ASP.NET guys maintain a different appdomain for every request ... but that doesn't seem feasible.
  • Another theory goes that the .Current method looks at the current Thread, and then uses that to look up the http context in some hashtable (or other static storage mechanism).

Either way, it's a technique that seems really useful ... I'd like to utilize it, but definitely don't want to be debugging shared state bugs :-/

+4  A: 

It isn't an AppDomain per-request. If you want to use thread-specific state, try:

[ThreadStatic]
private static int foo;
public static int Foo {get {return foo;} set {foo = value;}}

Each thread now gets its own value of Foo (or rather: 'foo').

This is not to be used lightly - it does have costs, but is a valid way of sharing state on a per-thread basis. I've used this once, maybe twice - and I've written a lot of C#. Don't over-use it...

In particular, watch out for initialization issues (i.e. forgetting to do it), and remember to clean up after yourself etc. And be very careful if you use any async code, as any callbacks/workers/etc will have different state.

Marc Gravell
awesome, thanks for this ... does the static instance get cleaned up once the thread dies?
Joel Martinez
Important to note that ThreadStatic isn't reliable in a high-load scenario. ASP.NET switches request contexts between threads and migrates the HttpContext. Any [ThreadStatic] will get left behind on the old thread, which is picking up a new request.
Rex M
Interesting question... especially if it is a pool thread that might be re-used ;-p My advice: clean up manually if you are doing this type of thing.
Marc Gravell
@Rex M - indeed. The above answer is mainly to indicate how you can achieve a similar effect in your regular code. ASP.NET can get... odd... about threading ;-p
Marc Gravell
+1  A: 

What Marc says is the easiest most likely for what you are after, however ASP.NET is actually somewhat more complicated than what say ThreadStatic does, because single requests actually can be processed by multiple threads.. what I believe happens with ASP.NET is that the executing thread explicitely is told to switch context, of course the hosting environment is scheduling the threads and it has context of which httpcontext needs executing, so it finds a thread, tells the thread which context it should run in.. then sends it off on its way.

So the solution really isn't all that pretty sadly, where as threadstatic is much simpler and probably suits needs 95% of the time.

meandmycode