WeakReference体验

 

Code
 1 using System;
2
3 namespace Demo
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 //实验1
10 Console.WriteLine("实验1,弱引用");
11 Object obj = new Object();
12 WeakReference wr = new WeakReference(obj);
13 obj = null;
14 GC.Collect();//取消注释结果将不一样,可以体会到垃圾回收的差异
15 Object obj2 = wr.Target;
16 if (obj2 == null)
17 {
18 Console.WriteLine("obj has collected!");
19 }
20 else
21 {
22 Console.WriteLine("obj is alive!");
23 }
24
25
26 //实验2,强引用
27 Console.WriteLine("实验2,强引用:");
28 Object o1 = new object();
29 Object o2 = o1;
30 o1 = null;
31 GC.Collect();
32
33 if (o2 == null)
34 {
35 Console.WriteLine("obj has collected!");
36 }
37 else
38 {
39 Console.WriteLine("obj is alive!");
40 }
41
42 Console.Read();
43 }
44 }
45 }

你可能感兴趣的:(WeakReference)