pre-分配(担保)内存在.NET应用程序应用程序、分配、存在、pre

2023-09-05 23:02:05 作者:默恋

是否有可能为一个.NET 3.5应用程序告诉.NET运行时:哎,我将使用的 N 的MB的内存后,所以请要么犯了太多的现在的或失败的现在的?

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?"

的上下文这就是:我有运行,返回大量的数据和数据库查询,然后执行它的一些处理一个C#控制台应用程序。查询可能需要很长的时间(小时)和内存使用率不断增加的结果看。查询完成后,有内存的直接秒杀因为我需要做的处理。如果计算机没有足够的RAM中的应用程序无法在这一点 - 对查询浪费时间了!这是非常令人沮丧的用户。如果没有足够的RAM,我想申请迅速失败。

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.

当然,我可以尝试一些黑客像分配一个大阵,我并不真的需要,然后将其设置为null之前我真正需要的内存,但是这并不理想,因为它实际上可能会导致进程运行时内存不足,否则它将有足够。理想情况下,我想使用不超过需要更多的内存,而只是早期的失败,除非一定量的可保证在整个时间我的应用程序运行。这可能吗?

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?

推荐答案

您可以尝试使用MemoryFailPoint类:

You could try to use the MemoryFailPoint class:

try
{
    using (new System.Runtime.MemoryFailPoint(20)) // 20 megabytes
    {
        ...
    }
}
catch (InsufficientMemoryException)
{
    ...
}