Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,124 | Comments: 45,475

filter by tags archive

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;

    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.



Why do you need the ConditionalWeakTable here though?

Ayende Rahien


Try putting anything else in its place

Patrick Huizinga


Because when a ThreadLocal instance is GCed, you want the value to be cleaned up with it. And since garbage collection is likely on a separate thread, you can't use the finalizer.


What's wrong with private static Holder _state; ?

Ayende Rahien


a) it won't be thread static?

b) it won't ever get cleaned up?


D'oh, I forgot that this is static... Been using ThreadLocal for too long!

Duarte Nunes

There's a disadvantage: if you have N threads using the ThreadLocal instance, and N-1 thread exit, then the values that they created will only be GCed when the Nth thread exits.

Since ConditionalWeakTable is already thread-safe, I would have:

private ConditionalWeakTable <thread,> _state;

and index with Thread.CurrentThread.

Duarte Nunes

Hm, let me try again: it's ConditionalWeakTable<Thread, Holder>.

Duarte Nunes

Oops, the ConditionalWeakTable is ThreadStatic. Nevermind my earlier post.


Hi Oren, very nice solution. I think this might be an excellent TDD excercise, do you have any tests that cover your implementation you can share to create a sort of kata on top of them?

Jon Wingfield

I don't get why you're not using a weak reference instead of the table. Not in silverlight either?


@Jon, I'd guess because you want the lifecycle of the Value to be tied to that of the TL instance, thus GCed when the TL instance is GCed but not earlier.

Jay R. Wren

My only thought was "be glad you have ConditionalWeakTable" I'd hate (or I'd like to see it, but I'd hate the added complexity) to see how you would have to do this in SL3 without CWT

Comment preview

Comments have been closed on this topic.


  1. RavenDB 3.5 whirl wind tour: You want all the data, you can’t handle all the data - one day from now
  2. The design of RavenDB 4.0: Making Lucene reliable - about one day from now
  3. RavenDB 3.5 whirl wind tour: I’ll find who is taking my I/O bandwidth and they SHALL pay - 3 days from now
  4. The design of RavenDB 4.0: Physically segregating collections - 4 days from now
  5. RavenDB 3.5 Whirlwind tour: I need to be free to explore my data - 5 days from now

And 14 more posts are pending...

There are posts all the way to May 30, 2016


  1. RavenDB 3.5 whirl wind tour (14):
    29 Apr 2016 - A large cluster goes into a bar and order N^2 drinks
  2. The design of RavenDB 4.0 (13):
    28 Apr 2016 - The implications of the blittable format
  3. Tasks for the new comer (2):
    15 Apr 2016 - Quartz.NET with RavenDB
  4. Code through the looking glass (5):
    18 Mar 2016 - And a linear search to rule them
  5. Find the bug (8):
    29 Feb 2016 - When you can't rely on your own identity
View all series



Main feed Feed Stats
Comments feed   Comments Feed Stats