ThreadStatic v.s. ThreadLocal<T>: is generic better than attribute?

C#GenericsAttributesThread LocalThreadstatic

C# Problem Overview


[ThreadStatic] is defined using attribute while ThreadLocal<T> uses generic. Why different design solutions were chosen? What are the advantages and disadvantages of using generic over attributes in this case?

C# Solutions


Solution 1 - C#

Something the blog post noted in the comments doesn't make explicit, but I find to be very important, is that [ThreadStatic] doesn't automatically initialize things for every thread. For example, say you have this:

[ThreadStatic]
private static int Foo = 42;

The first thread that uses this will see Foo initialized to 42. But subsequent threads will not. The initializer works for the first thread only. So you end up having to write code to check if it's initialized.

ThreadLocal<T> solves that problem by letting you supply an initialization function (as Reed's blog shows) that's run before the first time the item is accessed.

In my opinion, there is no advantage to using [ThreadStatic] instead of ThreadLocal<T>.

Solution 2 - C#

ThreadStatic Initialize only on first thread, ThreadLocal Initialize for each thread. Below is the simple demonstration:

    public static ThreadLocal<int> _threadlocal =
        new ThreadLocal<int>(() =>
        {
            return Thread.CurrentThread.ManagedThreadId;
        });

    public static void Main()
    {
        new Thread(() =>
        {
            for (int x = 0; x < _threadlocal.Value; x++)
            {
                Console.WriteLine("First Thread: {0}", x);
            }
        }).Start();

        new Thread(() =>
        {
            for (int x = 0; x < _threadlocal.Value; x++)
            {
                Console.WriteLine("Second Thread: {0}", x);
            }
        }).Start();

        Console.ReadKey();
    }

enter image description here

Solution 3 - C#

The main idea behind ThreadStatic is to maintain a separate copy of the variable for each thread.

class Program
    {
        [ThreadStatic]
        static int value = 10;

        static void Main(string[] args)
        {
            value = 25;

            Task t1 = Task.Run(() =>
            {
                value++;
                Console.WriteLine("T1: " + value);
            });
            Task t2 = Task.Run(() =>
            {
                value++;
                Console.WriteLine("T2: " + value);
            });
            Task t3 = Task.Run(() =>
            {
                value++;
                Console.WriteLine("T3: " + value);
            });

            Console.WriteLine("Main Thread : " + value);

            Task.WaitAll(t1, t2, t3);
            Console.ReadKey();
        }
    }

In the above snippet, we have a separate copy of value for each thread, including the main thread.

enter image description here

So, a ThreadStatic variable will be initialized to its default value on other threads except the thread on which it is created.

If we want to initialize the variable on each thread in our own way, use ThreadLocal.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2341923View Question on Stackoverflow
Solution 1 - C#Jim MischelView Answer on Stackoverflow
Solution 2 - C#maraiView Answer on Stackoverflow
Solution 3 - C#CSRView Answer on Stackoverflow