ThreadStatic v.s. ThreadLocallt;Tgt;: is generic better than attribute?(ThreadStatic 与 ThreadStatic 对比ThreadLocallt;Tgt;:泛型比属性好吗?)
问题描述
[ThreadStatic]
使用属性定义,而 ThreadLocal<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 static int Foo = 42;
使用它的第一个线程将看到 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>
通过让您提供一个在第一次访问项目之前运行的初始化函数(如 Reed 的博客所示)来解决该问题.
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<T>
没有任何优势.
In my opinion, there is no advantage to using [ThreadStatic]
instead of ThreadLocal<T>
.
这篇关于ThreadStatic 与 ThreadStatic 对比ThreadLocal<T>:泛型比属性好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ThreadStatic 与 ThreadStatic 对比ThreadLocal<T>:泛型比属性好吗?


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01