雁过请留痕...
代码改变世界

.Net中的内存分配问题

2013-09-29 15:13  xiashengwang  阅读(584)  评论(2编辑  收藏  举报

最近在测试的时候,要求测试内存不足的情况。我不想去开很多的程序来占用内存,那样太麻烦了,也不太精确。于是就写一个小程序来占用内存,想法很简单,就是声明一个Byte数组在占用内存,没想到这么简单的想法却没能正常工作,出乎我的所料,经过一番折腾,终于搞清楚了原因。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MemoryEat
{
    public partial class Form1 : Form
    {
        byte[] byteContainer;
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 分配内存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            int memorySize;
            if (int.TryParse(this.textBox1.Text, out memorySize))
            {
                if (memorySize > 0)
                {
                    byteContainer = new byte[memorySize * 1024 * 1024];
                    //关键就在这里 如果没有这个foreach,分配不成功的
                    //force commit the memory size
                    foreach (byte b in byteContainer)
                    {
                    }                   
                }
            }
        }

        /// <summary>
        /// 释放内存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (byteContainer != null)
            {
                byteContainer = null;
                GC.Collect();
            }
        }
    }
}

.Net中分配了一个数组后,并不会马上提交内存,你必须要访问到这个内存的时候,它才提交。这就是问题的原因。