【发布时间】:2016-07-15 14:20:36
【问题描述】:
我正在尝试了解垃圾收集过程,我想我明白了。但是当我处理一些代码时,它并没有像我预期的那样工作。 在下面的代码中,我刚刚创建了 1.000.000 对象并将它们添加到列表中。过了一会儿,没有对象,但内存卡住并且没有减少。删除所有对象后如何释放内存?
谢谢
private void button1_Click(object sender, EventArgs e)
{
List<Test> tesst = new List<Test>();
for (long i = 0; i < 1000000; i++)
{
using (Test test = new Test())
{
test.LongObj = i;
test.StrObj = i.ToString();
test.DecObj = Convert.ToDecimal(i);
tesst.Add(test);
}
}
Process proc = Process.GetCurrentProcess();
proc.Refresh();
label1.Text = Test.counter.ToString();
label2.Text = (proc.PrivateMemorySize64 / 1048576).ToString();
for (int i = 0; i < tesst.Count; i++)
{
tesst[i] = null;
}
tesst.Clear();
tesst = null;
}
private void button2_Click(object sender, EventArgs e)
{
Process proc = Process.GetCurrentProcess();
proc.Refresh();
label1.Text = Test.counter.ToString();
label2.Text = (proc.PrivateMemorySize64 / 1048576).ToString();
}
还有示例类
public class Test : IDisposable
{
public static long counter = 0;
public long LongObj { get; set; }
public string StrObj { get; set; }
public decimal DecObj { get; set; }
public Test()
{
Interlocked.Increment(ref counter);
}
~Test()
{
Interlocked.Decrement(ref counter);
}
public void Dispose()
{
}
}
【问题讨论】:
标签: c# memory memory-management garbage-collection