c# - 为什么我的 C# 应用程序出现内存不足异常?

标签 c# memory-management out-of-memory

我的物理内存是4G,但是为什么我只创建了1.5G的内存对象就出现内存不足的异常。任何想法为什么? (我同时看到,在任务管理器的性能选项卡中,内存没有被完全占用,我也可以在这里输入——所以内存实际上并不低,所以我想我遇到了其他一些内存限制)?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestBigMemoryv1
{
    class MemoryHolderFoo
    {
        static Random seed = new Random();
        public Int32 holder1;
        public Int32 holder2;
        public Int64 holder3;

        public MemoryHolderFoo()
        {
            // prevent from optimized out
            holder1 = (Int32)seed.NextDouble();
            holder2 = (Int32)seed.NextDouble();
            holder3 = (Int64)seed.NextDouble();
        }
    }

    class Program
    {
        static int MemoryThreshold = 1500; //M
        static void Main(string[] args)
        {
            int persize = 16;
            int number = MemoryThreshold * 1000 * 1000/ persize;
            MemoryHolderFoo[] pool = new MemoryHolderFoo[number];
            for (int i = 0; i < number; i++)
            {
                pool[i] = new MemoryHolderFoo();
                if (i % 10000 == 0)
                {
                    Console.Write(".");
                }
            }

            return;
        }
    }
}

最佳答案

在普通的 32 位 Windows 应用程序中,进程只有 2GB 的可寻址内存。这与可用的物理内存量无关。

所以 2GB 可用,但 1.5 是您可以分配的最大值。关键是你的代码不是进程中运行的唯一代码。其他 .5 GB 可能是 CLR 加上进程中的碎片。

更新:在 64 位进程的 .Net 4.5 中,如果 gcAllowVeryLargeObjects,您可以拥有大数组设置已启用:

On 64-bit platforms, enables arrays that are greater than 2 gigabytes (GB) in total size. The maximum number of elements in an array is UInt32.MaxValue.

<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>

关于c# - 为什么我的 C# 应用程序出现内存不足异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/597499/

相关文章:

c# - ASP.NET C# Repeater - 如何在没有 Javascript 的情况下将信息传回服务器?

c# - 为什么在 C# 中,在控件组合框中,我无法更改属性 SelectedItem?

c++ - 分配两个数组一次调用 cudaMalloc

c++ - 使用 C++ new[] 为二维数组分配内存

连续两次获取相同图像后的android位图内存不足错误

java - 导致内存不足异常的动画

java - 如何调试 Java OutOfMemory 异常?

c# - 有没有办法禁用从 UInt32 到 char 的隐式转换?

c# - 缩放时获取一组数据点

c++ - 存储在异常对象 : providing strings in exception 中的信息