ThreadStaticAttribute in ASP.NET
Asked Answered
C

2

21

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.

Convergence answered 25/1, 2011 at 8:16 Comment(0)
C
33

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:

This is a major PITA, because as far as I can see it mean the only persistence option for 'ThreadStatic'esque behavior in ASP.Net is to use HttpContext. So for your business objects, either you're stuck with the if(HttpContext.Current!=null) and the System.Web reference (yuck) or you've got to come up with some kind of provider model for your static persistence, which will need setting up prior to the point that any of these singletons are accessed. Double yuck.

Closing answered 25/1, 2011 at 8:19 Comment(5)
In this context, how ASP.NET is dealing with Thread Principal? If I set principal on site access in global.asax and use this principal along the way to check claims, etc., in the contexts that thread can change, does Asp.net copies principal, or thread culture for that matter?Fraxinella
@T.S.: Yes, I believe it does - but I'm not an ASP.NET expert, so I don't know the details.Closing
Any idea if this is also true for WebService (asmx) requests?Auditory
@Mt.Schneiders: I'd expect it to be true, but I'm not sure.Closing
of course [ThreadStatic] is much more likely to cause problems if you're using async in ASPNET - msdn.microsoft.com/en-us/magazine/dn802603.aspxPeterus
R
1

I'm not sure about using thread local data in ASP.NET environment, but .NET 4.0 comes with ThreadLocal class.

Rudd answered 25/1, 2011 at 9:35 Comment(1)
Thanks for the hint. Didn't know about that class. However it might also not work for the same reasons that Jon mentioned i guess?Convergence

© 2022 - 2024 — McMap. All rights reserved.