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.
WeakReference
would work, but if you can afford to dispose of instances explicitly, I would just go with that.MyObject
must correctly implementIDisposable
with a class destructor that calls.Dispose()
otherwise theWeakReference
toMyObject
will not be disposed.