• .Net中的内存分配问题


    最近在测试的时候,要求测试内存不足的情况。我不想去开很多的程序来占用内存,那样太麻烦了,也不太精确。于是就写一个小程序来占用内存,想法很简单,就是声明一个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中分配了一个数组后,并不会马上提交内存,你必须要访问到这个内存的时候,它才提交。这就是问题的原因。

  • 相关阅读:
    应用服务&领域服务
    Net程序调试
    node.js爬虫
    Amazon AWS S3 操作手册
    Spring MVC的异步模式DefferedResult
    mysql解决datetime与timestamp精确到毫秒的问题
    更改MySQL数据库的编码为utf8mb4
    MySQL中的表中增加删除字段
    Sublime Text 全程指引 by Lucida
    自定义多状态高仿应用下载百分数view
  • 原文地址:https://www.cnblogs.com/xiashengwang/p/3345763.html
Copyright © 2020-2023  润新知