I'm pretty sure this is a duplicate question, but I can't find the original(s).
I am getting some objects that I need to "attach" some information to. Basically, if that object ever gets back to the same piece of code, I need to see that I have seen it before.
ie. something like this:
Dictionary<WeakReference<ObjectType>, string> _Cache;
Note the weak reference in there (I know WeakReference is not generic btw), I need to make the key of the cache a weak reference, to handle the fact that the objects are GC'ed out of my control.
Now, I can make that cache full of weak references, but I seem to recall a similar type of system already existing in .NET, which was GC'ed automatically alongside the object.
Note that I do not recall the overhead of this, so I will make sure to read up on the subject before deciding if this is a good/better solution than my own cache. Unfortunately I cannot change the object in question, so I need to keep track of this meta-information somewhere else.
My limitations:
Basically, something like:
PropertyAttacher.Attach(instance, "Name", name);
Do I remember correctly? What are the classes involved?
You may be looking for .NET 4's ConditionalWeakTable<TKey, TValue>
Maybe you can build a dictionnary indexed by RuntimeHelpers.GetHashCode.
From MSDN:
RuntimeHelpers.GetHashCode is useful in scenarios where you care about object identity. Two strings with identical contents will return different values for RuntimeHelpers.GetHashCode, because they are different string objects, although their contents are the same.
EDIT: @Simon Mourier's solution seems to be a much better one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With