Thread Local Storage and Thread-Relative Static FieldsĀ 

You can use managed thread local storage (TLS) and thread-relative static fields to store data that is unique to a thread and application domain. Use thread-relative static fields if you can anticipate your exact needs at compile time. Use managed thread local storage when your actual requirements might only be discovered at run time.

In unmanaged C++, you use TlsAlloc to allocate slots dynamically and __declspec(thread) to declare that a variable should be allocated thread-relative. Thread local storage and thread-relative static fields provide the managed version of this behavior.

Thread Local Storage

Managed thread local storage provides dynamic data slots that are unique to a thread and application-domain combination. There are two types of data slots: named slots and unnamed slots. Named slots can be convenient, because you can use a mnemonic identifier. However, if another component uses the same name for its thread-relative storage, and a thread executes code from both your component and the other component, the two components might corrupt each other's data. You can avoid this by using a private unnamed data slot.

NoteNote

Both named and unnamed slots are thread specific. One thread cannot modify data from another thread, even when using the same named slot. A conflict can occur only if the same thread executes two different pieces of code that use the same named data slot.

To use managed TLS, simply create your data slot using Thread.AllocateNamedDataSlot or Thread.AllocateDataSlot, and use the appropriate methods to set or retrieve the information placed there.

Thread-Relative Static Fields

If you know that a field of your type should always be unique to a thread and application-domain combination, decorate a static field with the ThreadStaticAttribute. It is important to note that any class constructor code will run on the first thread in the first context that accesses the field. In all other threads or contexts, the fields will be initialized to null (Nothing in VisualĀ Basic) if they are reference types, or to their default values if they are value types. As a result, you should not rely on class constructors to initialize thread-relative static fields. Instead, you always assume that thread-relative static fields are initialized to null (Nothing) or to their default values.

See Also

Reference

ContextStaticAttribute
Thread.GetNamedDataSlot
ThreadStaticAttribute
CallContext

Other Resources

Managed Threading