Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. All threads of a process share the virtual address space of the process. The local variables of a function are unique to each thread that runs the function. However, the static and global variables are shared by all threads in the process. With thread local storage (TLS), you can provide unique data for each thread that the process can access using a global index. One thread allocates the index, which can be used by the other threads to retrieve the unique data associated with the index.
In the .NET Framework version 4, you can use the System.Threading.ThreadLocal<T> class to create thread-local objects.
where T Specifies the type of data stored per-thread. The ThreadLocal(Of T) type exposes the following members.
ThreadLocal(T)- The constructer used to initialize the ThreadLocal(T) instance.
ThreadLocal(T)(Tfunc(T))- This constructer is used to initialize the ThreadLocal(Of T) instance with the specified valueFactory function.
Value- This property is used to get or set the value of this instance for the current thread.
IsValueCreated- This property is used to get whether a value is initialized on the current thread.
Dispose()- This method is used to release all resources used by the current instance of the ThreadLocal(Of T) class.
Equals(Object)- This method determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Finalize()- This method is used to release the resources used by this ThreadLocal(Of T) instance. (Overrides Object.Finalize.)
GetHashCode()- This method serves as a hash function for a particular type. (Inherited from Object.)
GetType()- This method gets the Type of the current instance. (Inherited from Object.)
MemberwiseClone()- This method is uesd to create a shallow copy of the current Object. (Inherited from Object.)
ToString()- This method is uesd to create and return a string representation of this instance for the current thread. (Overrides Object.ToString.)
The .NET Framework provides dynamic data slots that are unique to a combination of thread and application-domain. There are two types of data slots: named slots and unnamed slots. Both are implemented by using the LocalDataStoreSlot structure.
To create a named data slot, use the Thread.AllocateDataSlot or Thread.GetNamedDataSlot method. To get a reference to an existing named slot, pass its name to the GetNamedDataSlot method.
To create an unnamed data slot, use the Thread.AllocateDataSlot method.
Read more: C# Corner