.NET 中是否有内置功能来创建线程绑定变量?
有没有办法做到这一点(伪代码):
GetCurrentThread().Items.Add(new RefObject);
然后稍后检索它
RefObject[] refObjs = GetCurrentThread().Items;
并枚举对象。显然,这两个调用将在同一线程的生命周期内发生。
基本思想是,我可以轻松地识别当前线程的项目,并且它们实际上是在该线程中创建的。它与使用 Page.Request
对象进行 ASP.NET 请求相同 - 您知道它在工作进程中非常独特,因此它不会与同时处理的其他请求混淆。我想像 Page.Request
一样对待线程 - 它来来去去,但当它处于活动状态时,我可以随意查询它,而无需关心进程中存在的其他威胁。
我曾经做过类似的事情,但它更多的是通过引用编组对象进行模拟。我可以想到更多的方法来做到这一点,但我真的不想自己手动存储线程和对象之间的映射。 .NET 中是否有类似于 TransactionScope 的线程?我对处理同步的困难和避免竞争条件不太感兴趣。
PS:如果这不可用,我可以至少为没有静态变量的 应用程序域 执行此操作吗?
Is there a way to do this (psedo code):
GetCurrentThread().Items.Add(new RefObject);
then later on retrive it
RefObject[] refObjs = GetCurrentThread().Items;
and enumerate the objects. Obviously both calls will occur on the same thread during the life span of it.
The basic idea is that I can easisly identify the items for the current thread were and that they are in fact created in this thread. It's same as using the Page.Request
object for an ASP.NET request - you know it's very unique in the worker process, so it doesn't get mixed up with other requests being served at the same time. I want to treat a thread like Page.Request
- it comes and then goes, but while it's alive, I can query it at will without caring about other threats that exist in the process.
Once I did something similar, but it was more of a simulation by marshaling objects by reference. And I can think of a couple of more ways to do it, but I really don't want to manually store the mapping between the thread and the object myself. Isn't there something similar to TransactionScope for threads in .NET? I am not too intersted in dealing with the hardship of syncronization and avoiding the race conditions.
PS: If that's not available, can I do it at least for an application domain without static variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 ThreadStatic 属性放在静态字段上。从那里,您可以构建您想要的任何特定于线程的数据。但是,您将无法从另一个线程访问数据(例如通过线程 ID)。
There is the ThreadStatic attribute that you can put on a static field. From there, you can build whatever thread-specific data you desire. However, you won't be able to access the data from another thread (by thread ID for example).
除了
[ThreadStatic]
(已经提到)之外,.NET 4.0 中还有ThreadLocal
- 大致相似,但它是一个只读的线程特定存储,使用基于委托的初始化。虽然值本身是只读的,但这可以是对可变对象的引用,提供特定于线程的对象模型。
ThreadLocal
的优点是它不必绑定到静态字段 - 例如,它可以在 lambda 主体的中间使用。但如果您不需要这个,[ThreadStatic]
更简单。In addition to
[ThreadStatic]
(already mentioned), in .NET 4.0 there isThreadLocal<T>
- which is broadly similar, but is a read-only thread-specific store that uses delegate-based initialization.While the value itself is read-only, this could be a reference to a mutable object, providing thread-specific object models.
An advantage of
ThreadLocal<T>
is that it doesn't have to be bound to a static field - it could be used (for example) in the middle of a lambda body. But if you don't need this,[ThreadStatic]
is simpler.