.NET弱引用
当把一个对象引用分配给一个变量时,该变量就包含对对象的一个强引用(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();
}