Shane Courtrille
Shane Courtrille

Reputation: 14097

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?

Upvotes: 10

Views: 2624

Answers (2)

user1228
user1228

Reputation:

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

This blog has some good info on ThreadStatic.

Upvotes: 15

MSN
MSN

Reputation: 54604

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.

Upvotes: 2

Related Questions