Dumbo
Dumbo

Reputation: 14122

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!

Upvotes: 1

Views: 3943

Answers (3)

Shai
Shai

Reputation: 25595

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?

Upvotes: 2

Johnny
Johnny

Reputation: 363

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?

Upvotes: 1

Mark H
Mark H

Reputation: 13907

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

Upvotes: 2

Related Questions