c# - 如何处理 OutOfMemoryException 直到它不再抛出?

标签 c# arrays exception int out-of-memory

我了解到 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/

相关文章:

c# - .NET 中的 SerialPort 是非托管资源吗?我的包装类是否正确?

javascript - Service Worker 缓存未将所有文件存储在数组中

jsp - 当属性无效时,我可以在自定义 JSP 标记中使用 JSTL 抛出异常吗?

javascript - TypeScript 中的异常嵌套/包装

java - AWS Lambda 调用异常 "No LambdaFunction annotation for method invoke"

c# - 非重复随机字母数字代码

c# - 遍历聚合

c# - System.Array.IndexOf 分配内存

javascript - 如何将数组值插入对象?

ruby-on-rails - 如何访问数组中的实例变量?