Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
06-Mar-2025ThreadLocal<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.