Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the availability of sufficient memory for an operation

Tags:

c#

memory

asp.net

Can we Determine the availability of sufficient memory for an operation? if yes, then how can? Thanks

like image 940
Muhammad Akhtar Avatar asked Oct 03 '10 10:10

Muhammad Akhtar


5 Answers

No, you absolutely cannot do this as you don't know in advance how much memory the operation will consume. If anyhow you know exactly how much memory the operation will consume you could query the available system memory and make an approximation but don't rely on it. Remember that Garbage Collection is pretty indeterministic and might kick in at any moment messing up with your approximations. You could get an OutOfMemoryException anytime.

So focus on writing quality code instead of this.

like image 82
Darin Dimitrov Avatar answered Oct 06 '22 05:10

Darin Dimitrov


For checking the available memory, I would suggest looking at this, this, this, but basically all you need to do is use a performance counter and do this:

PerformanceCounter pc = new PerformanceCounter("Memory","Available Bytes");
long availableMemory = Convert.ToInt64(pc.NextValue());
Console.WriteLine("Available Memory: {0}", availableMemory);

If you don't know how much memory the operation needs, though, checking available memory won't help you.

like image 24
Mia Clarke Avatar answered Oct 06 '22 06:10

Mia Clarke


You can check that there is not enough, if you have the minimum requirement and use the code from Banang.

But say you check the memory, next line you start your opperation, in the time between these 2 lines run another process starts that eats memory. You will then risk getting an out of memory exception.

like image 29
Shiraz Bhaiji Avatar answered Oct 06 '22 06:10

Shiraz Bhaiji


A possible work out can be using MemoryFailPoint Class and check for InsufficientMemoryException

like image 27
Zain Ali Avatar answered Oct 06 '22 06:10

Zain Ali


Yes, you can.
Let's say you know that operation will require 100 MB.

System.Runtime.MemoryFailPoint memFailPoint = null;
int memUsageInMB = 100;
bool isEnoughMemory = false;

try
{
    // Check for available memory.
    memFailPoint = new MemoryFailPoint(memUsageInMB);
    isEnoughMemory = true;
}
catch (InsufficientMemoryException e)
{
    // MemoryFailPoint threw an exception.
    Console.WriteLine("Expected InsufficientMemoryException thrown.  Message: " + e.Message);
}

if (isEnoughMemory)
{
    // Perform the operation.
}
else
{
    // Show error message.
}
like image 41
z-boss Avatar answered Oct 06 '22 06:10

z-boss