user2341923 user2341923 - 2 months ago 12
C# Question

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

[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?

Answer

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 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>.

Comments