[英]What's the best way to determine if NamedDataSlot exists
其實我想出了以下實現
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
...
您可以復制在GetNamedDataSlot源中觀察到的行為。
您可以引入特殊實體,比如Thread本地存儲適配器,它將維護已分配數據槽的字典。 應通過此實體進行所有數據槽分配。
這就是我的意思
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.