繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM