我了解到 C# 中的最大对象大小是 2GB。每台特定 PC 也有内存限制,它是 32 位或 64 位。
在我的应用程序中,我需要一个尽可能大的整数数组。所以我需要处理 OutOFMemoryException
直到可以创建最大可能的数组!
我最终得到以下代码:
private int[] AllIntegers()
{
int[] all;
int divider = 2;
try
{
all = new int[int.MaxValue];
}
catch (OutOfMemoryException)
{
all = new int[int.MaxValue / divider];
}
//Probably will fail again. how to efficently loop the catch again
for (int i = 0; i < all.Length; i++)
{
all[i] = i;
}
return all;
}
代码也会失败,我正在寻找一种正确的循环方式,直到可以制作数组!
最佳答案
编辑:我不喜欢这个想法,因为我认为保存如此大量的数据是错误的 (以及所有整数的数组?)
但是,这就是您要查找的内容:
static int[] AllIntegers()
{
int iSize = int.MaxValue;
int[] all;
int divider = 2;
while (true)
{
try
{
all = new int[iSize];
break;
}
catch (OutOfMemoryException)
{
iSize = iSize/divider ;
}
}
//Probably will fail again. how to efficently loop the catch again
for (int i = 0; i < all.Length; i++)
{
all[i] = i;
}
return all;
}
编辑 2: 也许向我们详细说明您要实现的目标?
关于c# - 如何处理 OutOfMemoryException 直到它不再抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551767/