Is it possible for a .NET 3.5 application to tell the .NET runtime: "hey, I'm going to use n MB memory later on, so please either commit that much now or fail now?"
The context for this is: I have a C# console application that runs a database query that returns a lot of data and and then does some processing on it. The query can take a very long time (hours) and memory usage keeps increasing as results are read. After the query finishes there is an immediate spike in memory due to the processing I need to do. If the machine doesn't have enough RAM the application fails at that point - after wasting hours on the query! This is very frustrating to the user. If there is not enough RAM I'd like the application to fail quickly.
Of course, I could try some hack like allocating a large array that I don't really need and then setting it to null just before I really need the memory, but this is not ideal, because it might actually cause the process to run out of memory when it would otherwise have enough. Ideally, I'd like to use no more memory than needed, but simply fail early on unless a certain amount can be guaranteed for the entire time my application runs. Is this possible?
Stack and Heap The Common Language Runtime (CLR) allocates memory for objects in these parts. Stack is a simple LIFO(last-in-first-out) structure. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is done when the program is compiled.
When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related to int data type are de-allocated in 'LIFO' fashion from the stack.
You could try to use the MemoryFailPoint
class:
try
{
using (new System.Runtime.MemoryFailPoint(20)) // 20 megabytes
{
...
}
}
catch (InsufficientMemoryException)
{
...
}
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