Azodious
Azodious

Reputation: 13872

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.

Upvotes: 2

Views: 1499

Answers (2)

ChrisWue
ChrisWue

Reputation: 19020

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.

Upvotes: 3

jeroenh
jeroenh

Reputation: 26772

It's documented here. You're using it the wrong way basically. You can't allocate a named slot twice:

If the AllocateNamedDataSlot method is used, it should be called in the main thread at program startup, because it throws an exception if a slot with the specified name has already been allocated. There is no way to test whether a slot has already been allocated.

Upvotes: 0

Related Questions