.NET 中 OutOfMemoryException 的 try/catch 块的设计模式
我有一个处理大量数据的应用程序,我想,有时可能会抛出 OutOfMemoryException
(半年来,我没有遇到任何异常,但我'我只是想知道这一切)。正如我所调查的,发生此异常后我无法继续执行我的程序。
是否有任何好的模式来处理此类异常,尤其是使用 IDisposable 类?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在真正的 OOM 场景中(在 x86 上比 x64 上更有可能),你注定会失败。几乎任何事情都会导致分配,所以你最好的选择是尽可能快地、优雅地死去,把伤害降到最低。
既然它没有发生,就不要过度强调,但是避免比在这里处理更好:
In a genuine OOM scenario (more likely on x86 than x64) you are pretty doomed there. Almost anything would cause an allocation, so your best option is to die as quickly and elegantly as possible, doing minimum harm.
Since it isn't happening, don't stress overly, but avoidance is better than handling here:
没有好的模式,OOM 是一种随时可能发生的令人讨厌的异常。这使得它几乎成为一个异步异常。处理它的唯一可能性是当您的代码被构造为同时分配大量内存时。因此,您将有可能退出并展开程序状态,就好像什么也没发生一样。
您需要设计您的程序,使其永远不需要分配超过所有可用虚拟内存的一半(在 32 位计算机上为 1 GB)。 Dragons 的寿命超过了这个数量,即使还有 500 MB 的虚拟内存未使用,您的程序也会在分配 90 MB 或更少的内存时失败。地址空间碎片引起的问题。如果您经常超过此阈值,那么您需要切换到 64 位操作系统。
There is no good pattern, OOM is a nasty exception that can strike at any moment. Which makes it almost an asynchronous exception. The only odds you have for handling it is when your code is structured to allocate large amounts of memory at the same time. So you'll have some odds to back out and unwind the program state as though nothing happened.
You need to design your program so it never needs to allocate more than about half of all available virtual memory, one gigabyte on a 32-bit machine. Dragons live beyond that amount, your program will fail on an allocation of 90 MB or less, even if there is another 500 MB of virtual memory unused. A problem induced by address space fragmentation. If you routinely cross this threshold then you need to switch to a 64-bit operating system.
我面前的两个答案是正确且合理的建议,
但有一件事他们没有提到——那就是负载测试。
如果您担心在特定负载下您的应用程序可能会耗尽内存,请针对该负载(最好是更大的负载)对其进行测试。
在我之前的工作中,我使用过这样的工具(HP 性能中心),事实证明,它不仅对于检查我们系统的错误和限制,而且对于识别瓶颈和昂贵的运营也非常有价值。
The two answers before mine are correct and sound advice,
but there's one thing they haven't mentioned - which is load testing.
If you're concerned that under certain load your application might run out of memory- test it against that load (and preferably- larger loads).
In my previous job I used such a tool (HP's Performance Center) and it proved invaluable not only to check for errors and limits of our system, but also in identifying bottlenecks and costly operations.