C# Design Patterns – Detecting When All But One Reference Are Destroyed

cdesign-patternsobject-oriented-design

In my application I have a class, and each instance of this class shares part of an unmanaged resource. Sharing is facilitated by a manager object.

When an instance is destroyed, the manager should be informed so it can re-purpose the allocated resources.

While I could make the programmer responsible for destroying the instance explicitly, I'd like to follow the model of the managed language as much as possible. That is, I'd like to leave it up to the runtime to determine when an object is eligible for destruction, and automatically inform the manager.

The problem is, the manager needs a list of all the instances to maintain their resources.

How can I keep a reference to a managed object, while still allowing it to be automatically destroyed when all other references are discarded?

To complicate it further, this particular application is very performance sensitive.

Best Answer

A simple approach is to have your manager track your objects with weak references. Weak references allow you to keep a reference to an object but the weak reference won't prevent it from being garbage collected.

var reference = new WeakReference<SomeType>(myObjectToManage);

// later
SomeType value;
if (reference.TryGetTarget(out value)) {
    // the object referenced is still alive.
}
else {
    // the object referenced has been garbage collected.
}

The only downside of this approach is the objects may live for a while after there are no references to them, until a garbage collection occurs.

Another option would be to implement your own reference counting scheme. This requires some discipline in the client code that is using these objects to make sure references are tracked correctly.

Related Topic