當第二個線程執行時,它會導致異常。你能解釋爲什麼嗎?訪問線程本地存儲
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