C Sharp

Reference-Counting Collection

Reference counting does a reasonable job of providing deterministic finalization in many cases. However, it's worth noting that in quite a few cases it doesn't, the most commonly cited example being cycles. In fact, straightforward reference counting never collects objects that participate in cycles. Most of us have painfully learned manual techniques to manage this, but using these techniques is an undesirable source of bugs. Also, if you start remoting objects across apartments, you can get apartment reentrancy and thus introduce a great deal of nondeterminism in your program. Some would argue that as soon as you hand a reference to an object outside the immediate control of a tightly coupled program, you have lost your deterministic finalization because you have no idea when or if that "foreign" code will release the reference. Others believe a complex system dependent on the order of termination of a complex graph of objects is an inherently brittle design likely to create a significant maintenance problem as the code evolves.

Tracing Collection

A tracing collector makes some weaker promises than reference counting does. It's a somewhat more lazy system with respect to executing termination code. Objects have finalizers, methods that are executed when the object is no longer reachable by the program. Tracing has the advantage that cycles are not an issue and the larger advantage that assigning a reference is a simple move operation-more on this shortly. The price that you pay is that there's no promise about termination code running "immediately" after a reference is no longer used. So, what's promised? The truth is that for well-behaved programs-an ill-behaved program is one that crashes or puts the finalizer thread in an infinite loop-the finalizers will be called for objects. The online documentation tends to be overly cautious about promises in this respect, but if an object has a Finalize method, the system will call it. This doesn't address the issue of deterministic finalization, but it's important to understand that resources will get collected and finalizers are an effective way to prevent resource leaks in a program.