Reputation: 4865
I've the following code. It may be dumb question, but I'm not sure, if synchronization is necessary or not.
class MyClass
{
[ThreadStatic]
private static object _staticObject;
private static readonly LockStaticField = new object();
public static object StaticObject
{
get
{
lock(LockStaticField)
{
return _staticObject ?? (_staticObject = new object());
}
}
}
}
I know ThreadStatic
fields doesn't need any synchronization because the state is not shared. But what is about the static getter and the initialization?
Upvotes: 3
Views: 1607
Reputation: 564333
I know ThreadStatic fields doesn't need any synchronization because the state is not shared. But what is about the static getter and the initialization?
This, too, would not need locking to synchronize, as the data (the backing field) will be unique per thread. You can safely remove the lock here.
Note that, as of .NET 4, you may want to also consider using ThreadLocal<T>
instead of [ThreadStatic]
to hold any local thread data. There are a few advantages, both in terms of usage (ie: IsValueCreated
), but also cleanup, as you can call Dispose()
to clean up all instances on all threads directly.
Upvotes: 8