.NET deterministic disposal of a shared object

130 views Asked by At

When multiple independent queues may hold references to the same managed object, what is a good method of deterministically disposing of that object when all the queues have finished referencing it?

Assume the object in question has both managed and unmanaged resources.

Note: Calling the Find() function to test all queues inside the dequeue function of one queue, isn't exactly what I had in mind.

1

There are 1 answers

0
supercat On BEST ANSWER

If consumers can be relied upon to call Dispose when they should, an interlocked reference count may suffice. If they cannot and if the guarded resource cannot compromise security even if it is recycled while still in use, one may guard the reference-counting object use a finalizer. If recycling the resource while it is in use could compromise security, then it may be necessary to have an object which keeps a list of long weak references to all consumers of the object and also maintains a static reference to that list. Any time any consumer is disposed, or the finalizer triggers on the guard object, it should (in thread-safe fashion) examine all the weak references and remove all those which have become invalid or identify already-disposed objects. If no references remain, the guard object should invalidate itself, remove the static reference to its list of weak references, and release the resource. If the guard object's finalizer triggered but references remain (as can happen in some resurrection scenarios), it should re-register for finalization.

Note that while a common pattern for performing atomic list updates is to use CompareExchange with a reference to an immutable list, using that technique would require that the reference be stored in something, other than the guard object, to which a static reference existed. Having the static reference identify the guard object would render the guard object's finalizer useless, but not having a static reference to the list of long weak references would risk having the system invalidate the references while the objects identified thereby still exist and could be resurrected.