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

前端 未结 3 1367
时光取名叫无心
时光取名叫无心 2020-11-30 01:19

[ThreadStatic] is defined using attribute while ThreadLocal uses generic. Why different design solutions were chosen? What are the advan

3条回答
  •  青春惊慌失措
    2020-11-30 01:34

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

提交回复
热议问题