当第二个线程执行时,它会导致异常。你能解释为什么吗?访问线程本地存储
class TLS
{
public void Run()
{
lock (this)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " started.");
LocalDataStoreSlot ldss = Thread.AllocateNamedDataSlot("unique"); // Exception
Thread.SetData(ldss, "some_data");
string a = Thread.GetData(ldss) as string;
Thread.Sleep(1000);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " ended.");
}
}
}
异常详细信息:
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) at System.LocalDataStoreMgr.AllocateNamedDataSlot(String name) at ConsoleApplication2.TLS.Run() in AutoLock.cs:line 65 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
感谢。
如果它是TLS,它不应该是每个线程唯一的。为什么每个线程都使用相同的插槽? – Azodious 2011-04-29 08:20:38
@Azodius:因为你做了两次。只需调用一次 - 具有该名称的插槽将分配给每个线程。只需阅读链接的MSDN文档,就可以解释它。 – ChrisWue 2011-04-29 08:39:36
好的。这意味着当插槽创建时,它会在每个线程的TLS中创建。 – Azodious 2011-04-29 09:00:53