Search code examples
c#multithreadingthread-local-storage

Accessing Thread Local Storage


When 2nd thread executes, it results in exception. Can you pls explain why?

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.");
        }
    }
}

Exception Details:

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

Thanks.


Solution

  • You are trying to allocate a slot with the same name twice. You might want to have a read over the MSDN documentation.

    Update: You should only allocate the slot once - before you start the threads. Do it in your main program. Right now you are doing it everytime a thread starts and that's why you are getting the exception.