user2341923 user2341923 - 1 year ago 144
C# Question

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

is defined using attribute while
uses generic.
Why different design solutions were chosen?
What are the advantages and disadvantages of using generic over attributes in this case?

Answer Source

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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download