When should I use ThreadLocal instead of Thread.SetData / Thread.GetData?

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 use compare with named data slots? Does ThreadLocal mean inherited by child threads? Is the idea that ThreadLocal is a simplified version of using named data slots? The following is an example of some material using the named data slots. Could this be simplified with ThreadLocal and will it retain the same properties as 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; } 
+4
source share
1 answer

It appears that the new ThreadLocal class is type-safe equivalent to the Thread.GetData / SetData API.

Local thread storage should never be inherited by "child threads" regardless of mechanism. TLS is, by definition, local to each individual flow.

Note that the [ThreadStatic] attribute provides TLS with .NET 2.0.

+2
source

Source: https://habr.com/ru/post/1380811/


All Articles