且构网

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

Httpclient内存增加缓慢问题-使用在所有情况下均已读取的任务

更新时间:2023-09-20 20:32:10

内存缓慢增加是完全正常的. .NET使用垃圾回收内存管理方法.现在,在运行集合的同时,所有其他线程已经停止了.这可能会导致人为的失速.这是GC和实时编程不能很好地融合的一个重要原因.

A slow memory increase is totally normal. .NET uses Garbage Collection Memory Management approach. Now while the collection runs, every other thread has to stop. This can cause human noticeable stalls. And is one big reason GC and realtime programming do not mix that well.

为了避免这些停顿,GC会在运行时保持惰性.它旨在仅运行一次-在应用程序关闭时.延迟不会那么明显.而且它甚至可以节省工作,因为内存将在之后移交给操作系统,并且不会被重复使用.由于没有运行终结器,因此可能没有太多工作要做.

To avoid those stalls, the GC is lazy with running. It is aiming for only running once - at application closure. Delays will not be that noticeable then. And it might even be able to save work, as the memory will be handed back to the OS afterwards and not be reused. Short of running finalizers, there might not be much work to be done.

只有几件事可以迫使它更早运行:

There are only a few things that can force it to run earlier:

  • 存在OutOfMemory异常的危险. GC将在可能发生异常之前收集并整理所有碎片.
  • 您致电GC.Collect();它允许您立即强制收集.请注意,这仅建议用于调试和测试.生产代码中不应包含此
  • 您选择了与桌面应用默认设置不同的GC策略.有一些人在anotehr线程中进行可达性检查,以使该工作不会暂停所有线程.定期运行但避免碎片整理的程序.即使是那些定期运行且运行时上限较高(以限制停顿)的机器.
  • there is a danger of a OutOfMemory exception. The GC will have collected and defragmented everything it possibly could before you ever get that Exception.
  • you call GC.Collect(); It allows you to force a collection now. Note that this only adviseable for debugging and testing. Production code should not have this
  • you pick a GC strategy that differs from Desktop applciation default. There are ones that do the reachabiltiy checks in anotehr thread, to have that work not pause all threads. Ones that run regulary but avoid defragmentation. Even ones that run regulary with a upper bound on runtime (to limit the stalls).