为什么内存不足取决于对GC.GetTotalMemory的中间调用? [英] Why does running out of memory depend on intermediate calls to GC.GetTotalMemory?

查看:151
本文介绍了为什么内存不足取决于对GC.GetTotalMemory的中间调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的内存密集型程序内存不足:抛出OutOfMemory异常。在尝试减少内存使用时,我开始调用GC.GetTotalMemory(true)(将调试文件的总内存使用量写入),这会触发垃圾收集。

出于某种原因,调用此函数时,我不会再遇到内存不足的异常。如果我再次删除调用(保持其他所有内容相同),则会再次抛出异常。根据我的理解,当内存压力增加时,调用会自动收集垃圾,所以我不理解这种行为。

任何人都可以解释为什么只有在GC.collect没有调用时才抛出内存不足异常吗?

更新:



我正在使用VS 2010,但我正在将应用程序定向到框架3.5。我相信碎片整理确实会导致我的问题。

我做了一些测试:抛出异常时,调用GC.gettotalmemory告诉我我正在使用〜800 * 10 ^ 6个字节。但是,任务管理器告诉我应用程序正在使用1700 MB。相当大的差异。我现在计划只分配一次内存,并且不会释放任何大型数组,而是重新使用它们。幸运的是,我的程序可以让我在没有太多大惊小怪的情况下完成此任务。

解决方案

我通过做一些更智能的内存管理来解决问题。特别是根据 http://www.simple-talk.com/dotnet/.net-framework/the-dangers-of-the-large-object-heap/


A memory intensive program that I wrote ran out of memory: threw an OutOfMemory exception. During attempts to reduce memory usage, I started calling GC.GetTotalMemory(true) (to write the total memory usage to debug file), which triggers a garbage collect.

For some reason, when calling this function I don't get an out of memory exception anymore. If I remove the calls again (keeping everything else the same), the exception gets thrown again. In my understanding, calls are automatically made to collect garbage when memory pressure increases, so I don't understand this behavior.

Can anyone explain why the out of memory exception is only thrown when there are no calls to GC.collect?

Update:

I'm using VS 2010, but I'm downtargeting the application to framework 3.5. I believe that defragmentation is indeed causing my problems.

I did some tests: When the exception is thrown, a call to GC.gettotalmemory tells me I am using ~800 * 10^6 bytes. However, task manager tells me the application is using 1700 mb. A rather large discrepancy. I'm now planning to allocate memory only once, and to never deallocate any large arrays but reusing them. Luckily, my program allows me to accomplish this without too much fuss.

解决方案

I solved the problem by doing some smarter memory management. In particular by using a CustomList according to the suggestions on http://www.simple-talk.com/dotnet/.net-framework/the-dangers-of-the-large-object-heap/

这篇关于为什么内存不足取决于对GC.GetTotalMemory的中间调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆