ThreadLocal storage in .NET

Similar to Lazy, ThreadLocal creates object local to one thread. So each individual thread will have its own Lazy initializer object and hence will create the object multiple times once for each thread. In .NET 3.5 or before, you can create objects that are local to one thread using ThreadStatic attribute. But sometimes ThreadStatic fails to create a truely ThreadLocal object. Basic static initializer is initialized for once, in case of ThreadStatic class.

ThreadLocal creates a wrapper of Lazy and creates a truly ThreadLocal object. Lets look into code how to build a ThreadLocal object.

public void CreateThreadLocal()
        {
            ThreadLocal<List<float>> local = new ThreadLocal<List<float>>(() => this.GetNumberList(Thread.CurrentThread.ManagedThreadId));

            Thread.Sleep(5000);

            List<float> numbers = local.Value;
            foreach (float num in numbers)
                Console.WriteLine(num);
           

        }

        private List<float> GetNumberList(int p)
        {
            Random rand = new Random(p);
            List<float> items = new List<float>();
            for(int i = 0; i<10;i++)
                items.Add(rand.Next();
            return items;
        }
&#91;/code&#93;

In the above methods, the <code>CreateThreadLocal </code>creates a local thread and takes the lazy object GetNumberList when the Value is called for (just like normal <code>Lazy </code>implementation).

Now if you call <code>CreateThreadLocal </code>using the code below, each of the Threads you create will hold its own List itself.


Thread newThread = new Thread(new ThreadStart(this.CreateThreadLocal));
            newThread.Start();
            Thread newThread2 = new Thread(new ThreadStart(this.CreateThreadLocal));
            newThread2.Start();

Remember, ThreadStatic objects has Thread affinity.

You can read more from here.

Hope this tip helps you

Thanks for reading.

DON'T MISS OUT!
Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434