Thread Safe Generic Weak Dictionary in .NET

If you are about to begin implementing your own version of a thread safe generic weak dictionary – STOP!

As of .NET 4.0, there is already one:

System.Runtime.CompilerServices.ConditionalWeakTable<TKey, TValue>

Now that .NET 4.5 has been made open source few weeks ago, we can look at the comments and more importantly at the implementation of ConditionalWeakTable<TKey, TValue>.


** Description: Compiler support for runtime-generated “object fields.”
** Lets DLR and other language compilers expose the ability to
** attach arbitrary “properties” to instanced managed objects at runtime.
** We expose this support as a dictionary whose keys are the
** instanced objects and the values are the “properties.”
** Unlike a regular dictionary, ConditionalWeakTables will not
** keep keys alive.
** Lifetimes of keys and values:
** Inserting a key and value into the dictonary will not
** prevent the key from dying, even if the key is strongly reachable
** from the value.
** Prior to ConditionalWeakTable, the CLR did not expose
** the functionality needed to implement this guarantee.
** Once the key dies, the dictionary automatically removes
** the key/value entry.
** Relationship between ConditionalWeakTable and Dictionary:
** ConditionalWeakTable mirrors the form and functionality
** of the IDictionary interface for the sake of api consistency.
** Unlike Dictionary, ConditionalWeakTable is fully thread-safe
** and requires no additional locking to be done by callers.
** ConditionalWeakTable defines equality as Object.ReferenceEquals().
** ConditionalWeakTable does not invoke GetHashCode() overrides.
** It is not intended to be a general purpose collection
** and it does not formally implement IDictionary or
** expose the full public surface area.
** Thread safety guarantees:
** ConditionalWeakTable is fully thread-safe and requires no
** additional locking to be done by callers.
** OOM guarantees:
** Will not corrupt unmanaged handle table on OOM. No guarantees
** about managed weak table consistency. Native handles reclamation
** may be delayed until appdomain shutdown.

Just by looking at the comments alone we can extrapolate that what we have is equivalent to a generic, thread safe weak dictionary! Further internet research, confirms the findings.

There are several critical limitations though:

  • TKey and TValue both have to be reference types
  • The equality is defined using ReferenceEquals()
  • GetHashCode() overrides are never called

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: