August 7th, 2013

Weak references have no effect on object lifetime

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.