We help IT Professionals succeed at work.

TLS in c#

mmingfeilam used Ask the Experts™
can someone show me how to implement TLS (thread local storage) in c#?  thanks.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
This is as simple as decorating a class member with the ThreadStatic attribute :

internal int myTLSValue;

Open in new window

Additionally you can also dynamically create and manage Thread Local Storage areas at runtime using the static method AllocateNamedDataSlot from the Thread class.


what about the callstack, how is it being managed within the TLS?  
Thread local storage is independent of the callstack. TLS is a mechanism where what looks to be a single class member is in fact duplicated in each thread.

This means that depending on which thread a method or property is invoked, it may "see" different values for the myTLSValue property from my sample.