我写了这个小测试程序:
在发布版中的输出结果为:
我假设GC.collect调用将会删除已分配的字符串,因为它们超出作用域,但看起来并不是这样。我不理解,也找不到解释。或许在这里有人能帮忙吗?
谢谢, Alex
using System;
namespace GCMemTest
{
class Program
{
static void Main(string[] args)
{
System.GC.Collect();
System.Diagnostics.Process pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
long startBytes = pmCurrentProcess.PrivateMemorySize64;
double kbStart = (double)(startBytes) / 1024.0;
System.Console.WriteLine("Currently using " + kbStart + "KB.");
{
int size = 2000000;
string[] strings = new string[size];
for(int i = 0; i < size; i++)
{
strings[i] = "blabla" + i;
}
}
System.GC.Collect();
pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
long endBytes = pmCurrentProcess.PrivateMemorySize64;
double kbEnd = (double)(endBytes) / 1024.0;
System.Console.WriteLine("Currently using " + kbEnd + "KB.");
System.Console.WriteLine("Leaked " + (kbEnd - kbStart) + "KB.");
System.Console.ReadKey();
}
}
}
在发布版中的输出结果为:
Currently using 18800KB.
Currently using 118664KB.
Leaked 99864KB.
我假设GC.collect调用将会删除已分配的字符串,因为它们超出作用域,但看起来并不是这样。我不理解,也找不到解释。或许在这里有人能帮忙吗?
谢谢, Alex
GC.Collect
方法是否会执行垃圾回收取决于某些隐藏变量,这是真的吗? - Phil Gan