10
[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?

Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366
Shane Courtrille
  • 13,960
  • 22
  • 76
  • 113

2 Answers2

15

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

This blog has some good info on ThreadStatic.

Sachin Joseph
  • 18,928
  • 4
  • 42
  • 62
  • That's where my example comes from. I'm just trying to figure out if it's possible for one thread to get _foo == null but then a thread switch occurs and another threads _foo gets new'ed up even though it isn't null? – Shane Courtrille Jul 06 '09 at 16:16
  • 1
    Nope. One _foo per thread, so context switches have no impact. –  Jul 06 '09 at 17:16
2

A [ThreadStatic] is compiler/language magic for thread local storage. In other words, it is bound to the thread, so even if there is a context switch it doesn't matter because no other thread can access it directly.

MSN
  • 53,214
  • 7
  • 75
  • 105