假设我有一个存储在BitmapImage对象中的大型Bitmap:
BitmapImage img = new BitmapImage();
无论出于何种原因,我需要添加更多指针:
BitmapImage p1 = img;
BitmapImage p2 = img;
BitmapImage p3 = img;
现在,如果我不再需要img,我将其设置为空指针:
img = null;
这样就足以让GC正常运转了吗?或者是否有必要执行以下操作:
p1 = null;
p2 = null;
p3 = null;
答案 0 :(得分:1)
根据为进程分配的内存输出,仅当最后一个指针设置为null时才释放内存。我使用了一个大的List,因为空的BitmapImage在内存中非常小。
Interactive C#:
> Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. var l = Enumerable.Repeat(123, 10000000).ToList();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
140423168
270663680
207835136
> Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
207761408
207761408
> Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. var p1 = l;
207831040
> Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
207851520
> var p2 = l;
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. var p3 = l;
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
208273408
208273408
> Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. l = null;
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. p1 = null;
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. p2 = null;
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
. p3 = null;
. System.GC.Collect();
. Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
208314368
208314368
208314368
208314368
141033472