Weak References

C# and Java both define weak references. If the only reference to an object is a weak reference, the object can be collected as garbage. Weak references are useful for referencing data that can easily be re-created and that should be freed if there is pressure for memory. Weak references are frequently used for cached data, where there is a performance improvement when the data is read from the cache but the data can be re-created if the cached information is collected.

The System.WeakReference class is used to create a weak reference. A weak reference is said to track an object, which is to say, maintain a weak association. There are two forms of weak reference, short-lived and long-lived. The difference is that long-lived weak references continue to track an object if it’s resurrected during garbage collection. (See the Resurrection section earlier in this appendix.) The WeakReference class takes the Object to track as a constructor argument.

  • The IsAlive property will return true if the object tracked by the WeakReference hasn’t been garbage-collected.

  • The TrackResurrection property can be used to determine and control whether the WeakReference is short-lived or long-lived.

  • The Target property returns the Object that’s being tracked, or null if the object has been garbage-collected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset