Does C# have a “ThreadLocal” analog (for data members) to the “ThreadStatic” attribute?

前端 未结 8 2239

I\'ve found the \"ThreadStatic\" attribute to be extremely useful recently, but makes me now want a \"ThreadLocal\" type attribute that lets me hav

8条回答
  •  春和景丽
    2020-12-14 08:59

    I ended up implementing and testing a version of what I had originally suggested:

    public class ThreadLocal
    {
        [ThreadStatic] private static Dictionary _lookupTable;
    
        private Dictionary LookupTable
        {
            get
            {
                if ( _lookupTable == null)
                    _lookupTable = new Dictionary();
    
                return _lookupTable;
            }
        }
    
    
        private object key = new object(); //lazy hash key creation handles replacement
        private T originalValue;
    
        public ThreadLocal( T value )
        {
            originalValue = value;
        }
    
        ~ThreadLocal()
        {
            LookupTable.Remove(key);
        }
    
        public void Set( T value)
        {
            LookupTable[key] = value;
        }
    
        public T Get()
        {
            T returnValue = default(T);
            if (!LookupTable.TryGetValue(key, out returnValue))
                Set(originalValue);
    
            return returnValue;
        }
    }
    

提交回复
热议问题