2011-11-11 163 views
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; 
    } 

回答

2

它看起来像新的ThreadLocal类是Thread.GetData/SetData API的类型安全的等价物。

线程本地存储永远不应该由“子线程”继承,不管机制如何。 TLS由各个线程定义。

请注意[ThreadStatic]属性自.NET 2.0开始就提供了TLS。

相关问题