An elegant ThreadLocal for Silverlight

time to read 3 min | 514 words

One of the annoying bits about Silverlight is how much of what I consider core API isn’t there. For example, concurrent collections or thread local.

I didn’t have the time to implement concurrent collections properly, but thread local isn’t really that hard. Here is a simple implementation:

public class ThreadLocal<T>
{
    private readonly Func<T> valueCreator;

    public class Holder
     {
         public T Val;
     }

    [ThreadStatic]
    private static ConditionalWeakTable<object, Holder> _state;

    public ThreadLocal():this(() => default(T))
    {
    }

    public ThreadLocal(Func<T> valueCreator)
    {
        this.valueCreator = valueCreator;
    }

    public T Value
    {
        get
        {
            Holder value;
            if (_state == null || _state.TryGetValue(this, out value) == false)
            {
                var val = valueCreator();
                Value = val;
                return val;
            }
            return value.Val;
        }
        set
        {
            if (_state == null)
                _state = new ConditionalWeakTable<object, Holder>();
            var holder = _state.GetOrCreateValue(this);
            holder.Val = value;
        }
    }
}

The fun part, it satisfies the entire contract, but I am willing to bet it is going to cause some head scratching.