Weak reference: Allows the object to be garbage collected while referencing the object.
. NET provides a WeakReference object to implement this functionality .
For those who create inexpensive but memory-intensive objects, you want to keep the object and use it when the application needs it.
Also, consider using weak references when you want the GC to be recycled when necessary. Weak references are simple to use.
WeakReference w = new WeakReference (XML);//Create a Reference object
if (w.isalive)//Determine if it has been garbage collected
{
XmlDocument XML1 = W.target as xmldocument;//convert to the specified object type to you
}
The WeakReference constructor has two overloads.
The following are references to other people's microblog, because they do not understand, not many.
Source: http://www.cnblogs.com/jeekun/archive/2011/10/09/2203712.html
In the previous article I mentioned that the object needing finalize will be resurrected before the final release, and we can probably guess the meaning of the second argument. If we give false the second argument, this weak reference is a short weak reference (weak reference), when the GC is reclaimed, found no reference to this object, it is considered useless, then the short weak reference to this object tracking end, weak reference Target is set to null. The constructor version of one of the preceding arguments creates a new weak reference for the short weak reference. If the second argument is true, the weak reference is a long weak reference (the longer weak reference). Target is available until the Finalize method of the object has not been executed. However, some of the member variables of the object may have been recycled, so use them to be careful.
Now let's see how WeakReference is implemented. It is obvious that WeakReference cannot directly refer to the target object, the Get/set of the target property of WeakReference is two functions, the reference to the target object is returned from somewhere, instead of directly returning or setting a private variable as we write most often. The GC maintains two lists to track the target objects of two weak references, and when a WeakReference object is created, it finds a location in the corresponding list, placing a reference to the target object, and it is clear that the two lists are not part of the root. When a GC is being reclaimed for memory, if an object is to be reclaimed, the list of weak references is checked, and if a reference to the object is saved, it is set to null.
C#weakreference Weak references