C# 什么时候应该使用ThreadLocal而不是Thread.SetData/Thread.GetData?

C# 什么时候应该使用ThreadLocal而不是Thread.SetData/Thread.GetData?,c#,multithreading,c#-4.0,C#,Multithreading,C# 4.0,在.net 4.0之前,我在System.Threading.Thread中使用命名数据槽实现了一个解决方案。现在,在.NET4.0中,有了ThreadLocal的概念。ThreadLocal用法与命名数据槽相比如何?ThreadLocal值是否由子线程继承?ThreadLocal是使用命名数据槽的简化版本吗?下面是一个使用命名数据槽的示例。这可以通过使用ThreadLocal来简化吗?它是否会保留与命名数据槽相同的属性 public static void SetSliceName(s

在.net 4.0之前,我在System.Threading.Thread中使用命名数据槽实现了一个解决方案。现在,在.NET4.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