垃圾收集器测试 [英] Garbage collector test

查看:161
本文介绍了垃圾收集器测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的.NET窗体应用程序来测试如何将其与垃圾收集器做清洁起来处理内存.NET的一些行为。

I have written a simple .net forms application to test some behaviour of .NET about how it handles memory together with the garbage collector to do the cleaning.

窗体应用程序界面看起来是这样的:

The forms application GUI looks like this:

和这样后面的代码:

public partial class Form1 : Form
{
    private readonly IList<byte[]> _btyList = new List<byte[]>();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < 3)
        {
            byte[] buffer = File.ReadAllBytes(@"C:\PFiles\20131018_nl_metro holland.pdf");
            _btyList.Add(buffer);
            i++;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < _btyList.Count)
        {
            _btyList[i] = null;
            i++;
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        GC.Collect();
    }
}

当我添加几个字节数组的私有字节数组列表它(当然)对应用程序的内存使用效果:

When I add a couple of byte arrays to the private list of byte arrays it (of course) has effect on the memory usage of the application:

现在,当我按清除键内存的内存使用量将保持不变。我可以等待小时,但它并没有改变。如果我按垃圾收集按钮(清除内存后),它会立即释放内存:

Now when I press the Clear memory button the memory usage will stay the same. I can wait for hours, but it doesn't change. If I press the Garbage collect button (after Clear memory) it will free the memory immediately:

现在的问题是:为什么垃圾收集不是在这种情况下工作。

The question is: Why does the garbage collector not work in this case?

推荐答案

垃圾收集不运行,因为它并不需要。如果内存不低,也没有必要收集。

The garbage collector isn't running because it doesn't need to. If memory is not low, there is no need to collect.

如果你有4GB内存,360MB的可能是下面的收集阈值。

If you have 4GB of memory, 360MB is probably below the collection threshold.

您不应该在一般情况下,有没有担心或思考时,GC运行,除非你正在写的时间或内存的关键代码。

You shouldn't, in general, ever worry or think about when the GC runs, unless you are writing time or memory critical code.

参考:垃圾收集基础

了解垃圾收集在.NET

垃圾收集发生当满足下列条件之一是
真:

Garbage collection occurs when one of the following conditions is true:


  • 该系统具有较低的物理内存

  • The system has low physical memory.

所使用的分配对象在托管堆中内存超过可接受的阈值。 作为进程运行此阈值连续调节。

The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.

该GC.Collect的方法被调用。在几乎所有情况下,你不必调用此方法,因为垃圾收集器连续运行
。这种方法主要用于特殊情况和
测试。

The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

这篇关于垃圾收集器测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆