2

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?

Dan Tao
  • 125,917
  • 54
  • 300
  • 447

1 Answers1

3

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.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 1
    It's hardly stupid. The .net libraries are very broad. Only the very patient or very bored have read through the docs enough times to know everything that is available. A general sense of the types of functionality available combined with google are the best way to find the bits you rarely need. – ScottS Jun 07 '10 at 18:07