ThreadLocal vs. local variable in C #

What is the difference between this ThreadName and LocalName in the code below? Are they both ThreadLocal?

// Thread-Local variable that yields a name for a thread ThreadLocal<string> ThreadName = new ThreadLocal<string>(() => { return "Thread" + Thread.CurrentThread.ManagedThreadId; }); // Action that prints out ThreadName for the current thread Action action = () => { // If ThreadName.IsValueCreated is true, it means that we are not the // first action to run on this thread. bool repeat = ThreadName.IsValueCreated; String LocalName = "Thread" + Thread.CurrentThread.ManagedThreadId; System.Diagnostics.Debug.WriteLine("ThreadName = {0} {1} {2}", ThreadName.Value, repeat ? "(repeat)" : "", LocalName); }; // Launch eight of them. On 4 cores or less, you should see some repeat ThreadNames Parallel.Invoke(action, action, action, action, action, action, action, action); // Dispose when you are done ThreadName.Dispose(); 
+5
source share
2 answers

LocalName not a local stream. It is designed to carry the surrounding lambda. You will get a new value every time the lambda works (and parallel runs are independent). With ThreadLocal you get a new value for the thread. Reusing ThreadName.Value will give you only one value if it is in the same thread.

In this example, both are equivalent because Thread.ManagedThreadId also thread-local. Try Guid.NewGuid() .

+2
source

There is a thread pool. Therefore, if the thread is reused for the second action, you will get "repeat". LocalName is a local variable.

0
source

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


All Articles