Over a million developers have joined DZone.

An elegant ThreadLocal for Silverlight

DZone's Guide to

An elegant ThreadLocal for Silverlight

Free Resource

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;

    private static ConditionalWeakTable<object, Holder> _state;

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

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

    public T Value
            Holder value;
            if (_state == null || _state.TryGetValue(this, out value) == false)
                var val = valueCreator();
                Value = val;
                return val;
            return value.Val;
            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.


Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}