.NET中本地的可继承线程 [英] Inheritable thread local in .NET
问题描述
.NET 4.0引入了 ThreadLocal<T>
类,这很棒.现在,我的应用程序用例需要类似Java的 InheritableThreadLocal
类. .NET中有类似的东西吗?如果不是,新线程如何用父线程中的变量初始化其线程局部变量?我想我需要使用初始化工厂方法,但不确定是什么放在那里.
.NET 4.0 introduced ThreadLocal<T>
class, which is great. Now, my app use case requires something like Java's InheritableThreadLocal
class. Is there anything like that in .NET? If not, how can a new thread initializes its thread locals variables with those from the parent thread? I suppose I need to make use the initialization factory method but not sure what to put in there.
推荐答案
The closest thing I can think of is using ILogicalThreadAffinitive and storing your object in the thread's CallContext with CallContext.SetData.
实现ILogicalThreadAffinitive的对象将流经逻辑上下文开关,例如BeginInvoke和ThreadPool.QueueUserWorkItem.还要注意,在使用线程池的情况下,此方法比使用ThreadLocals更安全,因为无法在线程上绞合"线程局部值并让另一个线程意外地将其取走.
Object implementing ILogicalThreadAffinitive will flow across logical context switches, such as BeginInvoke and ThreadPool.QueueUserWorkItem. Also note, this method is safer than using ThreadLocals for cases where you're using the thread pool because there's no way you can "strand" a thread local value on a thread and have another thread come and pick that up accidentally.
这篇关于.NET中本地的可继承线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!