dotNet weakReference
首先,关于GC:
1. 它不是基于引用计数的。那是COM用的东西,不够强壮而且expensive。
2. 只要一个对象有一个reference还在,它肯定不会被GC干掉;但是一个没有任何reference的对象,也只能成为一个candidate tobedeleted object对于GC而言。
3. GC.collect()可以被显式调用,并且确实可以做些事情,但是,不一定能干掉你想要干掉的对象,因为它只是一个candidate。
4. GC只有在memory pressure的时候才会开始干活。
对于weak reference而言:
1. 个人认为它的适用场合是:
1)创建这个对象很贵,并且对象很占内存,并且只在一定范围内使用它,并且希望使用完后立即从内存中删除它。
2)创建这个对象很便宜很方便,不适合用单例,但又要考虑内存消耗。需要的时候,check isAlive(),有就用,没有就重新创建。
2. 使用方法很简单,如下:
01.
// Create the object
02.
Book book =
new
Book(
"My first book"
,
"Me"
);
03.
// Set weak reference
04.
WeakReference wr =
new
WeakReference(book);
05.
// Remove any reference to the book by making it null
06.
book =
null
;
07.
08.
if
(wr.IsAlive)
09.
{
10.
Console.WriteLine(
"Book is alive"
);\
11.
Book book2 = wr.Target
as
Book;
12.
Console.WriteLine(book2.Title);
13.
book2 =
null
;
14.
}
15.
else
16.
Console.WriteLine(
"Book is dead"
);
17.
18.
// Lets see what happens after GC
19.
GC.Collect();
20.
// Should not be alive
21.
if
(wr.IsAlive)
22.
Console.WriteLine(
"Book is alive"
);
23.
else
24.
Console.WriteLine(
"Book is dead"
);
The output should be
Book is alive
My first book
Book is dead