Search code examples
.netmultithreadingthread-safetyinstancethreadstatic

Is there a straightforward way to have a thread-local instance variable?


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?


Solution

  • 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.