What is the ThreadLocal class in C#, and when is it useful?
Ask by ICSM Computer
Updated 06 Mar 2025
ThreadLocal<T>in C#The
ThreadLocal<T>class in C# provides thread-local storage, meaning that each thread accessing aThreadLocal<T>instance will have its own separate copy of the data. This ensures that the data is not shared between threads, preventing race conditions and unintended data modifications.It is part of the System.Threading namespace and is available in .NET Framework 4.0 and later.
Syntax
The
ThreadLocal<T>constructor takes a factory function (Func<T>) that initializes the value for each thread.Use Cases
Output (example)
Each thread gets a separate value, preventing unintended interference between threads.
Things to Consider
ThreadLocal<T>should be disposed to free thread-specific resources._threadLocalValue.Dispose();
AsyncLocal<T>for async operations orConcurrentDictionary<Thread, T>for manual management.