4
在.net 4.0之前,我使用System.Threading.Thread中的命名数据插槽实现了一个解决方案。现在,在.net 4.0中,有了ThreadLocal的概念。 ThreadLocal用法如何与指定的数据插槽进行比较? ThreadLocal值是否被子线程继承? ThreadLocal是使用命名数据插槽的简化版本吗?下面是使用命名数据插槽的一些例子。这可以通过使用ThreadLocal来简化,它是否会保留与指定数据插槽相同的属性?什么时候应该使用ThreadLocal而不是Thread.SetData/Thread.GetData?
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;
}