The .NET framework provides functionalities to store locally data that is specific to a thread and application domain. It’s called TLS, stand for Thread Local Storage.
It means that a when you store data locally, a thread within an application domain cannot modify an object from another thread once they are stored locally. Even if the threads use the same objects, their values may be different.
There are two different ways to store thread specific data locally using either static fields or data slots.
Pros and cons
1. Static fields: If you know in compile time the type of your fields you can count on static fields that have a better performance and compile time type checking;
2. Data Slots: If your code just knows in run time the type to be used, the data slot is the option. The drawback is that the data is stored in Object type members, casts must be performed and the execution is slower than static fields as well.
1. Static Fields
To define static fields to be stored locally we must use the ThreadStaticAttribute attribute like the following code:
static int myLocal;
That’s the only difference between a shared object and an object that is unique to a thread and application domain.
2. Data Slots
Data slots can be named or unnamed. If two different components create data slots with the same name, you may have problems related to data integrity when accessing from the same thread. On the other hand, for unnamed data slots you have to keep an instance of it.
To create them, you must use static methods under the Thread object and are implemented by the LocalDataStoreSlot class.
Thread.AllocateNamedDataSlot(string): Allocates a named data slot. A name is expected as a parameter;
Thread.GetNamedDataSlot(string): Retrives a named data slot;
Thread.AllocateDataSlot(): Allocates an unnamed data slot.
To retrieve values from data slots, you use the following methods:
Thread.SetData(LocalDataStoreSlot, object): Stores an object type containing a value to the specified data slot;
Thread.GetData(LocalDataStoreSlot): Retrieves an object type containing the value stored.
A very important issue is that the class constructor will run when the first thread accesses the class. It means that if you use class constructors to initialize static local fields, only the fields from the first thread will be initialized properly. Reference type fields will be null and value types will be set to its default value.
If you have the option, give preference to use strongly-typed static fields. They will be checked in compile time and casts will be unnecessary, reducing the overhead. Static fields will have better performance over the data slots.
If you want to check the MSDN pages related to TLS, click here!