线程静态和同步 [英] ThreadStatic and Synchronization
问题描述
我有以下代码.这可能是一个愚蠢的问题,但我不确定是否需要同步.
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());
}
}
}
}
我知道ThreadStatic
字段不需要任何同步,因为状态没有共享.但是静态获取器和初始化又如何呢?
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?
推荐答案
我知道ThreadStatic字段不需要任何同步,因为状态没有共享.但是静态获取器和初始化又如何呢?
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.
请注意,从.NET 4开始,您可能还需要考虑使用 ThreadLocal<T>
而不是[ThreadStatic]
来保存任何本地线程数据.就用法而言,有一些优点(即: IsValueCreated
),但是还可以进行清理,因为您可以调用Dispose()
直接清理所有线程上的所有实例.
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.
这篇关于线程静态和同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!