Weak references have no effect on object lifetime

Raymond Chen

The Weak­Reference class lets you retain a reference to an object while still permitting the object to be garbage collected. When that happens, then the Is­Alive property is false and the Target property is null. (Related discussion.) Note, however, that weak references do not alter the decision of the garbage collector whether or not an object is garbage. It merely lets you observe the garbage collector’s decision. Some people think that Weak­Reference means “Treat this as a regular (strong) reference most of the time, but if there is memory pressure, then you can reclaim the object.” This type of reference is called a Soft­Reference in Java, but the CLR has no analogous concept as far as I’m aware. In the CLR, weak references do not extend the lifetime of an object.

It’s sort of like the Prime Directive from Star Trek: Weak references follow a policy of non-interference with the natural course of the GC.

0 comments

Discussion is closed.

Feedback usabilla icon