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.
The [ThreadStatic] creates isolated versions of the same variable in each thread. Show activity on this post. The field marked with [ThreadStatic] are created on Thread Local Storage so every thread has it own copy of the field i.e the scope of the fields are local to the thread.
Thread Local Storage is used to store thread-specific pieces of data. Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. All threads of a process share the virtual address space of the process.
public static readonly object CounterLock = new object(); ... lock ( CounterLock ) { Counter++; } ... The point is that all reads / writes must be protected by the lock - it's not enough to protect a single place because then threads doing reads or writes may still make a change when a lock elsewhere is in effect.
Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With