本文介绍了ThreadStatic V.S. ThreadLocal的< T&GT ;:是通用比属性更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[ThreadStatic] 使用属性,而的ThreadLocal&LT定义; T> 使用通用的。
为什么不同的设计方案被选中?
有哪些优势,在这种情况下,使用通用属性上的缺点是什么?

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

推荐答案

东西的博客文章在评论中指出没有作出明确的,但我觉得是非常重要的,就是 [ThreadStatic] 不会自动初始化东西每个线程。例如,假设你有这样的:

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;

使用这个会看到的第一个线程初始化为 42 。但是,后续线程不会。初始化适用于只在第一个线程。所以,你最终不得不写code,检查它是否初始化。

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&LT; T&GT; 解决了,让你提供一个初始化函数(如芦苇的博客所示)这是第一次的项目被访问之前运行的问题。

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.

在我看来,没有任何优势,使用 [ThreadStatic] 而不是的ThreadLocal&LT; T&GT;

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

这篇关于ThreadStatic V.S. ThreadLocal的&LT; T&GT ;:是通用比属性更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 18:15