ThreadStatic 属性如何工作? [英] How does the ThreadStatic attribute work?

查看:28
本文介绍了ThreadStatic 属性如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[ThreadStatic] 属性如何工作?我假设编译器会发出一些 IL 来填充/检索 TLS 中的值,但是查看反汇编它似乎并没有在那个级别这样做.

How does [ThreadStatic] attribute work? I assumed that the compiler would emit some IL to stuff/retrieve the value in the TLS, but looking at a disassembly it doesn't seem to do it at that level.

作为后续,如果你把它放在一个非静态成员上会发生什么?我们有一个开发人员犯了这个错误,编译器甚至没有提供警告.

As a follow up, what happens if you put it on a non-static member? We had a developer make that mistake and the compiler doesn't even proffer up a warning.

更新

这里回答的第二个问题:ThreadStatic Modified with Static C#

Second question answered here: ThreadStatic Modified with Static C#

推荐答案

线程静态的实现语义低于 IL 级别,在 .NET jit 编译器中.像 VB.NET 和 C# 这样的向 IL 发出的编译器不需要了解有关 Win32 TLS 的任何信息,以便发出可以读写具有 ThreadStatic 属性的变量的 IL 代码.就 C# 而言,该变量没有什么特别之处——它只是一个读取和写入内容的位置.它具有属性这一事实对 C# 无关紧要.C# 只需要知道为那个符号名称发出 IL 读或写指令.

The implementation semantics of thread static are below the IL level, in the .NET jit compiler. Compilers that emit to IL like VB.NET and C# don't need to know anything about Win32 TLS in order to emit IL code that can read and write a variable that has the ThreadStatic attribute. There's nothing special about the variable as far as C# knows - it's just a location to read and write stuff. The fact that it has an attribute on it is of no consequence to C#. C# only needs to know to emit IL read or write instructions for that symbol name.

繁重的工作"由核心 CLR 完成,它负责使 IL 在特定硬件架构上工作.

The 'heavy lifting' is done by the core CLR that is responsible for making the IL work on a particular hardware architecture.

这也可以解释为什么将属性放在不合适的(非静态)符号上不会得到编译器的响应.编译器不知道该属性需要什么特殊语义.不过,像 FX/Cop 这样的代码分析工具应该知道它.

That would also explain why putting the attribute on an inappropriate (non-static) symbol doesn't get a reaction from the compiler. The compiler doesn't know what special semantics the attribute requires. Code analysis tools like FX/Cop, though, should know about it.

另一种看待它的方式:CIL 定义了一组存储范围:静态(全局)存储、成员存储和堆栈存储.TLS 不在该列表中,很可能是因为 TLS 不需要在该列表中.如果 IL 读写指令在用 TLS 属性标记符号时就足以访问 TLS,那么 IL 为什么要对 TLS 进行任何特殊表示或处理?不需要.

Another way to look at it: CIL defines a set of storage scopes: static (global) storage, member storage, and stack storage. TLS isn't on that list, very likely because TLS doesn't need to be on that list. If IL read and write instructions are sufficient to access TLS when the symbol is tagged with a TLS attribute, why should IL have any special representation or treatment for TLS? It's not needed.

这篇关于ThreadStatic 属性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆