Performance Quiz #10 — Thread local storage

It’s time for another quiz!

A very short one this time.  If I need some thread local storage and I might need several entries should I use:

Thread.GetData(slot) and Thread.SetData(slot, object)

or should I make my own static member like this

 static Dictionary<String,Object> myItems = new Dictionary<String,Object>;

and get things through the dictionary?

Warning: spoilers below in the comments … already 🙂  Maybe my quizzes are too easy 🙂

Comments (8)

  1. Alois Kraus says:

    Hi Rico,

    I think you should use the second attributed variant. Thread.GetData takes a process wide lock if I remember right which is a know scalability issue of .NET 2.0.

    Full Post is here:

    By the way I find the .NET Trace class has some design flaws in terms of performance and reliablity:


     Alois Kraus

  2. Alois Kraus says:

    Regardless of the bug I did mention above I think it is better to get the reference to the TLS data only once since it does cost more than a simple array/Hashtable access.

  3. ricom says:

    I’m going to have to add a spoilers warning now 🙂

  4. Alois Kraus says:

    Since your quiz was anounced as short I thought my answer could also be short and concise ;-).

    By the way Greg Young has some really great answers to very tricky  questions regarding for loops and JIT optimizations at assembly (not MSIL) level:

    Your blog is a great resource to advance my still incomplete knowledge about .NET. But it seems I have already made some progress ;-).


     Alois Kraus

  5. Mike Hearn says:

    And yet the Win32 TLS APIs do not take a global lock. Or at least, they shouldn’t need to: certainly Wines implementation of it doesn’t and neither does ELF TLS. So what went wrong here?

  6. Grim says:

    According to the MSDN documentation, you shouldn’t use inline initializers with static variables that bear the [ThreadStatic] attribute.

    From the MSDN entry:

    "Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread."

  7. I actually posted quiz #10 quite a while ago but a comment with the correct solution came in so quickly…

  8. I actually posted quiz #10 quite a while ago but a comment with the correct solution came in so quickly