When an object reference is assigned to a variable, the variable contains a strong reference to the object ). The garbage collector does not reclaim objects that are strongly referenced and are still in use. A strong reference is deleted only when the variable leaves the scope or is explicitly assigned null to the variable.
Weak reference can retain references to objects and allow the Garbage Collector to release objects and recycle memory at the time it deems appropriate. Assume that the creation of an object is relatively cheap, but it consumes a lot of memory. If you want to keep this objectProgramYou need to use it, but you also want to be able to tell the Garbage Collector to reclaim the memory when necessary.
Weak references can be referenced through the weakreference class.
In the following exampleCodeAt the beginning of the ASP. NET application, a 32 KB string is created, the string is allocated to a weakreference instance, and the weak reference is placed in the Application Object for future retrieval. After the bigstring variable in application_start leaves the scope, there will be no strong reference to the string instance.
VoidApplication_start (ObjectSender, eventargs e) {string bigstring =NewString ('A', 32768); weakreference weakref =NewWeakreference (bigstring); application. Add ("Bigstring", Weakref );}
If you can access the application object search string before the garbage collection occurs, the target attribute of the weakreference object will contain an object reference to the string. If the target attribute is empty, the weak referenced object will be garbage collected. To use this string, you must recreate it. Otherwise, you can extract the target attribute and use the bigstring variable to create a strong reference, and then use the created String object at the beginning of the application.
Protected VoidPage_load (ObjectSender, eventargs E)
{
If(! Ispostback)
Getbigstring ();
}
Private VoidGetbigstring ()
{
Weakreference;
If(Application ["Bigstring"]! =Null)
{
Weakreference = application ["Bigstring"]AsWeakreference;
String bigstring;
Bigstring = weakreference. TargetAsString;
If (bigstring! = null )
lbmessage. TEXT = " bigstring retrieved from weakreference ";
else
lbmessage. TEXT = " bigstring was garbage collected ";
}
Else
Lbmessage. Text ="Unable to retrieved bigstring from Application";
}
Protected VoidBtngc_click (ObjectSender, eventargs E)
{
GC. Collect ();
Getbigstring ();
}