确定 NamedDataSlot 是否存在的最佳方法是什么
实际上我想出了以下实现
bool DoesNamedDataSlotsExist(string name)
{
try
{
Thread.AllocateNamedDataSlot(name);
}
catch
{
return true;
}
return false;
}
这里明显的问题:如果某些代码调用 DoesNamedDataSlotExist()
两次,它将首先生成 false
然后 true
(如果我使用 Thread.FreeNamedDataSlot() 可以优化...)
但是有更好的方法吗?
编辑
GetNamedDataSlot
的来源
public LocalDataStoreSlot GetNamedDataSlot(string name)
{
LocalDataStoreSlot slot2;
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.ReliableEnter(this, ref tookLock);
LocalDataStoreSlot slot = (LocalDataStoreSlot) this.m_KeyToSlotMap[name];
if (slot == null)
{
return this.AllocateNamedDataSlot(name);
}
slot2 = slot;
}
finally
{
if (tookLock)
{
Monitor.Exit(this);
}
}
return slot2;
}
不知何故,我需要访问 this.m_KeyToSlotMap
...
Actually I come up with the following implementation
bool DoesNamedDataSlotsExist(string name)
{
try
{
Thread.AllocateNamedDataSlot(name);
}
catch
{
return true;
}
return false;
}
The obvious problem here: If some code calls DoesNamedDataSlotExist()
twice, it will first generate false
then true
(which could be optimized if i would use Thread.FreeNamedDataSlot()
...)
But is there any better way?
EDIT
source of GetNamedDataSlot
public LocalDataStoreSlot GetNamedDataSlot(string name)
{
LocalDataStoreSlot slot2;
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.ReliableEnter(this, ref tookLock);
LocalDataStoreSlot slot = (LocalDataStoreSlot) this.m_KeyToSlotMap[name];
if (slot == null)
{
return this.AllocateNamedDataSlot(name);
}
slot2 = slot;
}
finally
{
if (tookLock)
{
Monitor.Exit(this);
}
}
return slot2;
}
Somehow I would need to access this.m_KeyToSlotMap
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以复制在 GetNamedDataSlot 源中观察到的行为。
您可以引入特殊实体,例如线程本地存储适配器,它将维护已分配的数据槽的字典。所有数据时隙的分配都应通过该实体进行。
这就是我的意思
You can duplicate the behavior you observe in GetNamedDataSlot source.
You can introduce special entity, say Thread local storage adapter, that will maintain the dictionary of already allocated data slots. All allocations of data slots should be made via this entity.
Here's what I mean