The ThreadStaticAttribute

Friday, March 11, 2005

Thread local storage (TLS) was a fun way to piggyback data into the thread environment block (TEB) in the old days. You can ask each thread in a process to reserve a location to store your special data, say for example, a pointer to a data structure representing a database transaction. No matter where the thread goes, you can always pull the transaction reference out of TLS and go to work – no function parameters required!

The managed equivalent of TLS is the ThreadStaticAttribute class.

Taking advantage of TLS has always been tricky in an environment using thread pooling. As Scott Hanselman and Jef Newsom point out – ASP.NET uses a thread pool, and one has to take extreme care using the ThreadStaticAttribute in ASP.NET. The majority of people asking about using TLS have not really wanted to track a resource associated with a thread, but a resource associated with an HTTP request - which is just what HttpContext.Items is in place to take care of.

I’ll offer up one more reason to avoid ThreadStatic in ASP.NET, and that is the new Async page feature coming in ASP.NET 2.0 (@Page Async=”True”).

Instead of blocking request threads during processing of web service calls to say, Reporting Services, marking an ASP.NET 2.0 Page as Async allows the thread to hop back into the pool and process other requests. When the web request finishes, a thread will return to finish rendering the page. Will it be the same thread? I don’t have proof yet but I would seriously doubt it will be guaranteed. Use TLS and you'll certainly be pooched sooner or later.

There is not a lot out yet about Async pages in 2.0 – I’m interested to see if it will be working in the Feb CTP. Looks like Frtiz Onion has an example up already.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!