且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制通过的MemoryStream占用释放内存?

更新时间:2023-11-28 08:01:04

我不认为这个问题是垃圾收集器不能做的工作。如果GC正在内存pressure它应该运行并收回你刚刚分配的400 MB的。

I don't think the problem is the garbage collector not doing its job. If the GC is under memory pressure it should run and reclaim the 400 MBs you've just allocated.

这是更可能下降到GC没有找到一个 contigious 400 MB 块。

This is more likely down to the GC not finding a contigious 400 MB block.

相反,一个内存不足的错误发生,因为这个过程是无法   找到的连续未使用的页面有足够大的部分其   虚拟地址空间执行请求的映射。

Rather, an "out of memory" error happens because the process is unable to find a large enough section of contiguous unused pages in its virtual address space to do the requested mapping.

您应该阅读埃里克利珀的博客文章内存不足并不是指物理内存

You should read Eric Lippert's blog entry "Out Of Memory" Does Not Refer to Physical Memory

您是好得多做下面的两个

  1. 重用你已经分配的内存块(你为什么要创建一个使用完全相同的尺寸)
  2. 分配更小的块(小于 85KBs

此前DOTNET 4.5,DOTNET构建了两个堆,小对象堆(SOH)大对象堆(LOH)。请参阅大对象Hearp改进在.NET 4.5 通过布兰登布雷。你的的MemoryStream 被分配在LOH,而不是压缩(碎片整理)为过程的持续时间,使得它更可能是多次调用分配此大量的内存会抛出一个 OutOfMemoryException异常

Prior to Dotnet 4.5, Dotnet constructed two heaps, Small Object Heap (SOH) and Large Object Heap (LOH). See Large Object Hearp Improvements in .NET 4.5 by Brandon Bray. Your MemoryStream is being allocated in LOH, and not compacted (defragmented) for the duration of the process, making it much more likely that multiple calls to allocate this large amount of memory will throw an OutOfMemoryException

在CLR管理两个不同的堆分配,小对象   堆(SOH)和大对象堆(LOH)。任何分配更大   大于或等于85000个字节的推移蕙。复制大对象   有性能损失,因此LOH不板结​​不像SOH。   另一个定义特征是LOH只收集   期间,第2代集合。总之,这些有内置的   假设大对象分配是罕见的。

The CLR manages two different heaps for allocation, the small object heap (SOH) and the large object heap (LOH). Any allocation greater than or equal to 85,000 bytes goes on the LOH. Copying large objects has a performance penalty, so the LOH is not compacted unlike the SOH. Another defining characteristic is that the LOH is only collected during a generation 2 collection. Together, these have the built-in assumption that large object allocations are infrequent.