What is the best way to determine if NamedDataSlot exists

I actually come up with the following implementation

bool DoesNamedDataSlotsExist(string name) { try { Thread.AllocateNamedDataSlot(name); } catch { return true; } return false; } 

The obvious problem is here: if some code calls DoesNamedDataSlotExist() twice, it will generate false first, then true (which could be optimized if I used Thread.FreeNamedDataSlot() ...)

But is there a better way?

EDIT

source 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 will need to access this.m_KeyToSlotMap ...

+4
source share
1 answer

You can duplicate the behavior that you observe in the source GetNamedDataSlot.

You can enter a special object, for example, a localization adapter, which will support a dictionary of already allocated data slots. All data slot allocations must be made through this object.

Here 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; } } } 
+3
source

Source: https://habr.com/ru/post/1342625/


All Articles