When should ThreadLocal be used instead of Thread.SetData/Thread.GetData?
- by Jon Ediger
Prior to .net 4.0, I implemented a solution using named data slots in System.Threading.Thread. Now, in .net 4.0, there is the idea of ThreadLocal. How does ThreadLocal usage compare to named data slots? Does the ThreadLocal value get inherited by children threads? Is the idea that ThreadLocal is a simplified version of using named data slots? An example of some stuff using named data slots follows. Could this be simplified through use of ThreadLocal, and would it retain the same properties as the named data slots?
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;
}