When should ThreadLocal be used instead of Thread.SetData/Thread.GetData?

Posted by Jon Ediger on Stack Overflow See other posts from Stack Overflow or by Jon Ediger
Published on 2011-11-11T17:37:20Z Indexed on 2011/11/11 17:51 UTC
Read the original article Hit count: 216

Filed under:
|
|

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;
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading