ThreadLocal

This lesson discusses the ThreadLocal class in C#

We'll cover the following

ThreadLocal

A ThreadLocal<T> object creates a copy of the type parameter T for every thread that accesses it. Since each thread receives a copy of its own to manipulate, no locking constructs are required when a thread mutates its own copy. However, the ThreadLocal<T> class does offer methods to make each copy accessible across all threads.

Consider the example below in which we have five threads that compute the squares of the integers passed-in and then store the result in a thread local integer. The output shows that each thread has its own distinct copy.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.