如何获取另一个线程的ThreadStatic值? [英] How to get ThreadStatic value of another thread?
问题描述
是否有可能给定Thread
引用以获取该线程的ThreadStatic
值?
Is it possible given the Thread
reference to get ThreadStatic
value for that thread?
推荐答案
否,这是不可能的.与此类属性一样,[ThreadStatic]
属性可被抖动识别.它生成对CLR的调用,以获得指向类的线程本地存储的指针.此帮助程序方法有多种版本,基本的是JIT_GetSharedGCThreadStaticBase()
.但是对于通用类来说,它变得更加复杂,例如,它可以基于类型参数具有多个静态变量. helper函数采用两个不明显的参数,即模块ID和类ID.这些ID取决于加载代码的AppDomain.
No, that's not possible. As common with attributes like this one, the [ThreadStatic]
attribute is recognized by the jitter. It generates a call into the CLR to obtain a pointer to the thread-local storage for a class. There are multiple versions of this helper method, the basic one is JIT_GetSharedGCThreadStaticBase()
. But it gets more convoluted for a generic class for example, it can have multiple static variables based on the type parameter. The helper function takes two non-obvious arguments, the module ID and the class ID. Those IDs depend on the AppDomain in which the code was loaded.
长话短说,您没有机会进行相同的调用,帮助方法甚至也没有获取线程ID,这是调用上下文所隐含的.
Long story short, you don't stand a chance to make this same call, nor does the helper method even take the thread ID, it is implied by the call context.
您可以使用Thread.AllocateNamedDataSlot()
将任意数据挂起在线程外.但是请注意,它是静态方法,也不使用线程ID,它还是基于调用上下文.
You can hang arbitrary data off a thread with Thread.AllocateNamedDataSlot()
. But note that it is static method and doesn't take a thread ID either, it is again based on the call context.
这都是故意的.线程本地存储的一个很好的特性是它始终是线程安全的.允许从另一个线程访问它的后门将完全破坏该功能.如果您想这样做,那会让您非常担心.例如,您可以使用以ManagedThreadId为关键字的自己的查找表.
This is all quite intentional. A very nice property of thread-local storage is that it is always thread-safe. A backdoor that would permit accessing it from another thread would completely destroy that feature. Something that should worry you a great deal if you want to do this. You could, with, say, your own lookup table that's keyed by the ManagedThreadId.
这篇关于如何获取另一个线程的ThreadStatic值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!