Take the 2-minute tour ×

For a remoting framework, I need to keep some metadata about object that I'm returning. I have no control over the object themselves (so I can't make them IDisposable), I also don't know their type. my only assumption is that it's a reference type.

The problem is life time, when do I free my metadata.

I intend to create a static dictionary(ConcurrentDictionary) and hold there a WeakReference to the object, and the metadata. The question is, how do i know when to delete the metadata? is there a way to receive a notification when the object itself is finalized?

Also i don't care about necromancy (object resurrection)

Thank you

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

If you're using .NET4 or later you could possibly use ConditionalWeakTable<K,V>.

This would mean that you (probably) wouldn't need to worry about freeing-up the metadata yourself: it would just disappear from the table once the object itself was gone.

The ConditionalWeakTable<TKey, TValue> class differs from other collection objects in its management of the object lifetime of keys stored in the collection. Ordinarily, when an object is stored in a collection, its lifetime lasts until it is removed (and there are no additional references to the object) or until the collection object itself is destroyed. However, in the ConditionalWeakTable<TKey, TValue> class, adding a key/value pair to the table does not ensure that the key will persist, even if it can be reached directly from a value stored in the table (for example, if the table contains one key, A, with a value V1, and a second key, B, with a value P2 that contains a reference to A). Instead, ConditionalWeakTable<TKey, TValue> automatically removes the key/value entry as soon as no other references to a key exist outside the table.

share|improve this answer
add comment

You do not get a signal when a specific object is collected.

Your best option is indeed to combine the meatadata with a weak reference and periodically scan the collection.

share|improve this answer
add comment

Although generally not advised, you could also write your own finalizer so you knwo when the object is finalized. The ConditionalWeakTable suggestion sounds like it is geared towards what you aretrying to accomplish.

share|improve this answer
add comment

Your Answer


