访问线程本地存储
当第二个线程执行时,会导致异常。你能解释一下为什么吗?
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(对象键、对象 nvalue、布尔值添加) 在 System.LocalDataStoreMgr.AllocateNamedDataSlot(字符串名称) 在 AutoLock.cs 中的 ConsoleApplication2.TLS.Run() 处:第 65 行 在 System.Threading.ExecutionContext.Run(ExecutionContextexecutionContext,ContextCallback 回调,对象状态) 在 System.Threading.ThreadHelper.ThreadStart()
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正尝试两次分配同名的插槽。您可能需要阅读 MSDN 文档。
更新:您应该只分配一次槽 - 在启动线程之前。在您的主程序中执行此操作。现在,每次线程启动时您都会执行此操作,这就是您收到异常的原因。
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: