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

2

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?

Usn answered 6/7, 2009 at 15:24 Comment(0)
H
15

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

This blog has some good info on ThreadStatic.

Hairless answered 6/7, 2009 at 15:30 Comment(2)
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?Usn
Nope. One _foo per thread, so context switches have no impact.Hairless
W
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.

Whitecollar answered 6/7, 2009 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.