Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-allocate (guarantee) memory in a .NET application

Tags:

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?

like image 798
EM0 Avatar asked Jan 22 '15 23:01

EM0


People also ask

How does memory allocation happen in C#?

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.

How stack memory is cleared in C#?

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.


1 Answers

You could try to use the MemoryFailPoint class:

try
{
    using (new System.Runtime.MemoryFailPoint(20)) // 20 megabytes
    {
        ...
    }
}
catch (InsufficientMemoryException)
{
    ...
}
like image 91
Dmitry Avatar answered Nov 04 '22 08:11

Dmitry