We help IT Professionals succeed at work.

TLS in c#

mmingfeilam
mmingfeilam used Ask the Experts™
on
can someone show me how to implement TLS (thread local storage) in c#?  thanks.
Comment
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 :

[ThreadStatic]
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.

Author

Commented:
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.