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 a class that implements that functionality and it’s called ConditionalWeakTable and it exists in System.Runtime.CompilerServices namespace.
There are however several limitations: both the key and the value have to be reference types (TKey : class and TValue : class).
Here is the comment from the source file:
** 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