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();
LocalName
is not thread-local. It is scoped to the execution of the surrounding lambda. You will get a fresh value each time the lambda runs (and concurrent runs are independent). With a ThreadLocal
you get a fresh value per thread. Repeatedly invoking ThreadName.Value
will only give you one value if it happens to be on the same thread.
In this example both are equivalent because Thread.ManagedThreadId
is also thread-local. Try Guid.NewGuid()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With