什么时候应该使用ThreadLocal而不是Thread.SetData/Thread.GetData ?
本文关键字:Thread SetData GetData ThreadLocal 什么时候 | 更新日期: 2023-09-27 18:14:07
在。net 4.0之前,我在System.Threading.Thread中实现了一个使用命名数据槽的解决方案。现在,在。net 4.0中,有了ThreadLocal的概念。如何使用ThreadLocal比较命名数据槽?是否ThreadLocal值被子线程继承?是不是认为ThreadLocal是使用命名数据槽的简化版本?下面是一个使用命名数据槽的例子。这可以通过使用ThreadLocal来简化吗?它会保留与命名数据槽相同的属性吗?
public static void SetSliceName(string slice)
{
System.Threading.Thread.SetData(System.Threading.Thread.GetNamedDataSlot(SliceVariable), slice);
}
public static string GetSliceName(bool errorIfNotFound)
{
var slice = System.Threading.Thread.GetData(System.Threading.Thread.GetNamedDataSlot(SliceVariable)) as string;
if (errorIfNotFound && string.IsNullOrEmpty(slice)) {throw new ConfigurationErrorsException("Server slice name not configured.");}
return slice;
}
看起来新的ThreadLocal类是Thread的类型安全等效物。GetData/SetData API。
无论采用何种机制,线程本地存储永远不应该被"子线程"继承。根据定义,TLS对每个线程都是本地的。请注意,[ThreadStatic]属性自。net 2.0以来一直提供TLS。