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

查看:208
本文介绍了如何在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与静态C#修改

Second question answered here: ThreadStatic Modified with Static C#

推荐答案

静态线程的执行语义是低于IL水平,在.NET JIT编译器。能发出来IL喜欢VB.NET和C#编译器并不需要了解Win32的TLS以发出的IL代码,可以读取和写入具有ThreadStatic属性变量什么。有没有什么特别的变量,只要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.

另一种方式来看待它:CI​​L定义了一组存储范围:静态的(全球)存储,成员存储和栈存储。 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天全站免登陆