views:

221

answers:

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

+5  A: 

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

This blog has some good info on ThreadStatic.

Will
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?
ShaneC
Nope. One _foo per thread, so context switches have no impact.
Will
A: 

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