在 .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。
关于c# - 什么时候应该使用 ThreadLocal 而不是 Thread.SetData/Thread.GetData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8097807/