我的物理内存是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/