[英]What's the best way to determine if NamedDataSlot exists
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()
...) 这里显而易见的问题是:如果某些代码调用
DoesNamedDataSlotExist()
两次,它将首先生成false
然后为true
(如果我使用Thread.FreeNamedDataSlot()
可以优化它...)
But is there any better way? 但还有更好的方法吗?
EDIT 编辑
source of GetNamedDataSlot
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
... 不知怎的,我需要访问
this.m_KeyToSlotMap
...
You can duplicate the behavior you observe in GetNamedDataSlot source. 您可以复制在GetNamedDataSlot源中观察到的行为。
You can introduce special entity, say Thread local storage adapter, that will maintain the dictionary of already allocated data slots. 您可以引入特殊实体,比如Thread本地存储适配器,它将维护已分配数据槽的字典。 All allocations of data slots should be made via this entity.
应通过此实体进行所有数据槽分配。
Here's what I mean 这就是我的意思
internal static class TLSAdapter
{
static Dictionary<string, LocalDataStoreSlot> tlsSlots = new Dictionary<string, LocalDataStoreSlot>();
public static bool DoesNamedDataSlotsExist(string name)
{
lock(tlsSlots)
{
return tlsSlots.ContainsKey(name);
}
}
public static LocalDataStoreSlot AllocateNamedDataSlot (string name)
{
lock(tlsSlots)
{
LocalDataStoreSlot slot = null;
if ( tlsSlots.TryGetValue(name, out slot) )
return slot;
slot = Thread.GetNamedDataSlot(name);
tlsSlots[name] = slot;
return slot;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.