有没有一种简单的方法来拥有线程局部实例变量?
通过 ThreadStatic 属性,我可以拥有一个类的静态成员,每个线程有一个对象实例。这对于使用不保证线程安全实例方法的对象类型(例如,System.Random
)来实现线程安全来说非常方便。
不过,它仅适用于static
成员。是否有任何直接的方法可以将类成员声明为线程本地成员,这意味着每个类实例每个线程都有一个对象?
With the ThreadStatic
attribute I can have a static
member of a class with one instance of the object per thread. This is really handy for achieving thread safety using types of objects that don't guarantee thread-safe instance methods (e.g., System.Random
).
It only works for static
members, though. Is there any straightforward way to declare a class member as thread-local, meaning, each class instance gets an object per thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来像
ThreadLocal
类就是我一直在寻找的。是的,我确实觉得之前不知道这一点有点愚蠢。
Looks like the
ThreadLocal<T>
class is what I was looking for.And yes, I do feel a bit stupid for not knowing about this before now.