开发者

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 = Threa开发者_C百科d.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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜