views:

138

answers:

3

Where can I find good implementation of IDictionary which uses weak references inside?

Dictionary should be holding only weak references to values and eventually clean up itself of dead references.

Or should I just write it myself?

+1  A: 

I think if you just use the WeakReference as value inside the dictionary that you'll have exactly what you need.

See also this link, which does exactly the same to build a cache

http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

Henri
+3  A: 

You'll need to write it yourself. It should be relatively straight forward, implementing the IDictionary interface and then storing the actual values as WeakReferences. You can then check the values on add/select to see if they're still alive.

Sudo code - won't really compile:

public class WeakDictionary <TKey,TValue> : IDictionary<TKey,TValue>
{
    private IDictionary<TKey,WeakReference> _innerDictionary = new Dictionary<TKey,WeakReference>();


    public TValue Index[ TKey key ]
    {
        get{
            var reference = _innerDictionary[ key ];
            if( reference.IsAlive )
                return (TValue)reference.Target;
            throw new InvalidOperation( "Key not found." );
        }

    }

    private void Cull()
    {
        var deadKeys = new List<TKey>();
        foreach( var pair in _innerDictionary )
        {
            if( ! pair.Value.IsAlive )
                deadKeys.Add( pair.Key );
        }

        foreach( var key in deadKeys )
            _innerDictionary.Remove( key );
    }
}
Paul Alexander