Search code examples
multithreadingthread-safetythread-static

Is this a thread safe way to initialize a [ThreadStatic]?


[ThreadStatic]
private static Foo _foo;

public static Foo CurrentFoo {
   get {
     if (_foo == null) {
         _foo = new Foo();
     }
     return _foo;
   }
}

Is the previous code thread safe? Or do we need to lock the method?


Solution

  • If its ThreadStatic there's one copy per thread. So, by definition, its thread safe.

    This blog has some good info on ThreadStatic.