I have a component that needs to store static values fore each thread. It’s a general component that can be used in many scenarios and not only in ASP.NET.
I was thinking to use the [ThreadStatic] attribute to achieve my goal. Supposing that it would also work fine in ASP.NET scenarios, because i was assuming that every Request is called in a own thread.
After some research i found this Blog Post from Scott Hanselman saying to be careful when using [ThreadStatic] in ASP.NET.
However most of the comments (below the Post) do not agree with that was Scott wrote, saying that a Request always run in one thread and that the thread is not used by another request at the same time. That’s also what I believe but would love to have some opinion about you experts in here.
Nope, Scott is right: a request definitely doesn’t have to run on a single thread for its entire duration. ASP.NET is thread-agile in that respect. There are only a few points where the switch can happen, but it definitely can happen. (I’ve tested it for myself.)
You may wish to read this blog post and this Spring forum thread for some more details.
Basically you should find a different way of capturing context. The relevant bit from your point of view is probably at the end of the blog post: