Can we Determine the availability of sufficient memory for an operation? if yes, then how can? Thanks
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.
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.
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.
A possible work out can be using MemoryFailPoint Class and check for InsufficientMemoryException
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With