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:
To illustrate the use of the WeakReference class, the WeakReference sample has been built that reads into memory all of the documents in a specific docs directory that have the suffix of .txt. These documents were retrieved primarily from the Project Gutenberg (http://www.gutenberg.net) to make this sample a little more real. One screenshot of the running program is shown in Figure 10.12. The source for this application is in the WeakReference subdirectory.
The program attempts to read into memory all of the documents in the docs directory that have a suffix of .txt. Each time a document is read into memory, a WeakReference is made to that memory and the strong reference is removed, thereby making that memory available for collection. The program automatically adapts to the RAM that is installed on your computer. If you have little RAM, then only a few documents will be able to be read into memory without causing a garbage collection cycle. In contrast, if you have more RAM, more documents will be able to fit into RAM without triggering a garbage collection cycle. Running this under the debugger, you can tell when a document has been retained in memory from the message Target in memory that will appear in the output window of the IDE.
3.144.86.134