下面的代码中这个ThreadName和LocalName有什么区别?它们都是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();
答案 0 :(得分:3)
LocalName
不是线程本地的。它的范围是周围lambda的执行。每次lambda运行时,您将获得一个新值(并且并发运行是独立的)。使用ThreadLocal
,您可以获得每个帖子的新值。重复调用ThreadName.Value
只会在同一个线程上提供一个值。
在这个例子中,两者都是等价的,因为Thread.ManagedThreadId
也是线程局部的。试试Guid.NewGuid()
。
答案 1 :(得分:2)
有一个线程池。因此,如果一个线程被重用于第二个动作,你将得到&#34;重复n#34;。 LocalName是一个局部变量。