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…
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