确定NamedDataSlot是否存在的最佳方法是什么

时间:2011-03-07 11:21:05

标签: c# .net multithreading

实际上我想出了以下实现

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

1 个答案:

答案 0 :(得分:3)

您可以复制在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;            
        }       
    }   
}