WeakReference or Racing with the Garbage Collector

As long as an application root references an object, it is said to have a strong reference to it. As long as an object has a strong reference, the garbage collector cannot collect it. The .NET Framework also has the concept of a weak reference. A weak reference allows the programmer to retain access to an object; however, if the runtime requires memory, the object that is referenced by the weak reference can be collected.

It is all about timing. To use the WeakReference class, you need to follow the next steps:

1.
Allocate memory to be used as a buffer, an object, and so on. The variable that references the allocated memory is now the strong reference to this object.
2.
Construct a WeakReference ...

Get .NET Common Language Runtime Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.