6

I am looking for a good pattern to implement ref counting in C#. I have a

Dictionary<string, MyObject> ObjList;

What I want to do is hand out references to MyObject instances if they exist and create new ones if they don't. Multiple places in my code may make a reference to a MyObject instance but when all are freed up I would like to remove it from my dictionary. I have looked into WeakReference but Im not sure if it is applicable here??

Edit 1.) Specifics I am using an OPC Server so whenever I reference an Item I would like to use the dictionary to lookup existing references to the item. When I dont need the item anymore I want to unsubscribe from the item. It isnt easy to know when or how many place in my code are currently using the item.

4
  • It's not clear at all what you're trying to do... Jan 26, 2016 at 0:51
  • What I am doing is using an OPC server so when a object has no references I want to unsubscribe from it. I am under the impression that my dictionary will always have a reference so it will never be disposed
    – MDK
    Jan 26, 2016 at 0:52
  • WeakReference would work, but if you can afford to dispose of instances explicitly, I would just go with that.
    – Ry-
    Jan 26, 2016 at 1:00
  • 1
    It is important to note that MyObject must correctly implement IDisposable with a class destructor that calls .Dispose() otherwise the WeakReference to MyObject will not be disposed. Jul 29, 2018 at 2:11

2 Answers 2

6

What I have done in these scenarios is create a dictionary of WeakReferences. What a WeakReference does is allow your dictionary to refer to an instance of MyObject without keeping that instance in memory. Therefore, once all the other references to that object have been freed, an entry for the item will still exist in the dictionary. However, that entry will refer to a WeakReference where IsAlive is false and the Target is null. If you want, you can occasionally clean up the dictionary by removing all the entries where the WeakReference is not alive.

4

This is the kind of thing you need:

public class WeakReferences<T>
{
    private Func<string, T> _factory;

    public WeakReferences(Func<string, T> factory)
    {
        _factory = factory;
    }

    private Dictionary<string, WeakReference> _references =
        new Dictionary<string, WeakReference>();

    public T this[string index]
    {
        get
        {
            T target = default(T);
            if (_references.ContainsKey(index))
            {
                var wr = _references[index];
                target = (T)wr.Target;
                if (wr.IsAlive)
                {
                    Console.WriteLine("Reused: " + index);
                    return target;
                }
            }
            target = _factory(index);
            _references[index] = new WeakReference(target);
            return target;
        }
    }
}

You can use it like this:

    Func<string, object> f = k =>
    {
        Console.WriteLine("Created: " + k);
        return new object();
    };

    var wrs = new WeakReferences<object>(f);

    var a = wrs["a"];
    var b = wrs["b"];
    a = wrs["a"];
    b = wrs["b"];
    a = null;
    GC.Collect();
    a = wrs["a"];
    b = wrs["b"];

The output I get running this is:

Created: a
Created: b
Reused: a
Reused: b
Created: a
Reused: b
6
  • The tricky part is how would you perform code the cleanup code. In your example above how would you get. Deleted: a. I need to place code to tell the Opc server I'm done
    – MDK
    Jan 26, 2016 at 12:20
  • @MDK - You don't need to tell this to clean-up at all. It's all weak references - once you no longer have any references elsewhere in your code all of this will be cleaned up by the GC. Jan 26, 2016 at 12:59
  • @MDK - If the objects you are adding need to be disposed of then it would be trivial to remove the need for the Func<string, T> factory and allow external assignment of the instances so that you can manage disposal yourself. Jan 26, 2016 at 13:01
  • So I guess your saying there is no automatic way to tell when an object is dereferenced. I didnt want to rely on other users of my code to explicitly dispose of objects.
    – MDK
    Jan 26, 2016 at 21:55
  • 1
    @MDK - You must explicitly dispose of your objects. The garbage collector does not do it automatically. So it doesn't help you to be able to check if the object is referenced or not. Nonetheless you can check the IsAlive property of a WeakReference to see if it has been garbage collected or not. But again, this does not tell you if it has been disposed or not. I think you might need to let us know how you need to manage the lifetime of your objects so that we can advise you on the best way to go. Jan 26, 2016 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.