I'm looking for a way of caching data for the lifetime of a thread. The data doesn't need to be accessible across threads. In ASP.NET, you can do this using the HttpContext.Current.Items collection. Anything you store in here is retained as long as the thread is alive, and is accessible from any class. I was wondering if there's a more generic equivalent in the .NET framework (4.0) which isn't tied to HTTP.
Thanks,
Dan.
VulpesPosted May 22, 2013, 4:45 AM
You can create as many ThreadLocal
Thread.AllocateNamedDataSlot does, as you say, allocate a named data slot on all threads. However, each thread has its own copy of this named slot and so they can't interfere with each other.
The purpose of thread local storage is to give each thread its own copy of a storage location rather than create storage for one thread in isolation which (as I understand it) is ideally what you want.
Local variables on the thread's stack achieve the latter objective and, as long as there's only a single method call in the thread's execution path, it's really all you need.
However, if there are multiple method calls in the thread's execution path, you have to pass the local variables from method to method which can be awkward in practice. That's really the problem which thread local storage is designed to solve.
Dan CouparPosted May 22, 2013, 6:05 AM
I couldn't use the valueFactory approach because the function required access to instance data.
Many thanks for taking the time to explain it all.
Dan CouparPosted May 21, 2013, 4:41 PM
Thread.SetData looks promising, but I'm not sure I like the sound of the method comment for Thread.AllocateNamedDataSlot, which says "Allocates a named data slot on all threads". Ideally I want it to do that only on the current thread when execution reaches that point in the code... or is that what it means?
VulpesPosted May 21, 2013, 4:07 PM
Check out my article on the subject:
http://www.c-sharpcorner.com/UploadFile/b942f9/thread-local-storage-of-data-in-net/