當把一個對象引用分配給一個變數時,該變數就包含對對象的一個強引用(strong reference)。垃圾收集器不會收回強引用仍在使用的對象。只要當變數離開範圍,或者顯示地給變數分配null時,強引用才被刪除。
弱引用(weak reference)可以保持對對象的引用,同時允許垃圾收集器在它認為適當的垃圾收集時間釋放對象,回收記憶體。假設有一個對象建立相對便宜,但需耗費大量的記憶體,如果希望保持這個對象,在應用程式需要使用它,但也希望能夠告訴垃圾收集器,在必要時把記憶體收回。
弱引用可以通過WeakReference類引用。
在下面的執行個體代碼中,在ASP.NET應用程式開始時建立了一個32KB的字串,把字串分配給一個WeakReference執行個體,並把弱引用放在Application對象中供以後檢索。在Application_Start中的bigString變數離開範圍後,將不存在對字串執行個體的強引用。
void Application_Start(object sender, EventArgs e) { String bigString = new String('A', 32768); WeakReference weakRef = new WeakReference(bigString); Application.Add("BigString",weakRef); }
如果能在垃圾收集發生之前訪問Application對象檢索字串,WeakReference對象的Target屬性將包含對字串的一個對象引用。如果Target屬性為空白,被弱引用的對象就已經被執行垃圾收集了。要使用就要重新建立這個字串。否則,可以提取Target屬性並用bigString變數建立一個強引用,然後在應用程式的開始處使用所建立的字串對象。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetBigString();
}
private void GetBigString()
{
WeakReference weakReference;
if (Application["BigString"] != null)
{
weakReference = Application["BigString"] as WeakReference;
String bigString;
bigString = weakReference.Target as String;
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 void btnGC_Click(object sender, EventArgs e)
{
GC.Collect();
GetBigString();
}