How to handle OutOfMemoryException until it does not throw again?

I got to know the maximum object size in C# is 2GB. Also there is a memory limit for each particular PC and either it is 32 or 64 bit.

In my application I need an array of integers as big as possible. So what I need is to take care of OutOFMemoryException until the biggest possible array can be made!

I end up with the code below:

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;
}

the code will also fail, what I am looking for is a proper way of looping untill the array can be made!

Answers


EDIT: I do not like the idea of this, since I think it's wrong to hold such a large amount of data (and an array of all integers?)

But, here's what you're looking for:

    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;
    }

EDIT2: Maybe elaborate us with what you are trying to achieve?


Use a System.Runtime.MemoryFailPoint to check if sufficient resources are available before attempting to allocate the object.


It is always not a good idea to hold such big array in memory.

Can't you split your big array into small ones, and based on range to load appropriate array?


Need Your Help

Inserting data into one table with two foreign keys

php mysql insert foreign-keys point-of-sale

I have two tables (for POS system) named: purchase and product. The columns of the purchase table are: poid (PK, auto_increment), prodid (FK), poquantity. The columns of the product table are: prodid

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.