Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 290
Helic Avatar asked Aug 22 '14 10:08

Helic


1 Answers

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().

like image 157
usr Avatar answered Oct 12 '22 09:10

usr