Best way to avoid out of memory exception in application

谁说胖子不能爱 提交于 2019-12-06 05:51:31

Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory.

Handling exception is easiest solution, though may bring different difficulties and inconsistencies into the application with time. Another way would be getting available size of memory resources like this:

Process currentProcess = Process.GetCurrentProcess();
long memorySize = currentProcess.PrivateMemorySize64

Then you can calculate the length of your queue based on estimate of one object memory capacity.

Another way would be to check for memory size in each worker thread. Whenever there's no memory, the thread can just finish. This way many threads would be spawning and dying but the application would be at maximum available capacity.

You can and probably should use the MemoryFailPoint class in a scenario like this.

If you get an OutOfMemoryException then the application state could be corrupt and you shouldn't try to recover from it. MemoryFailPoint is designed to avoid this by allowing you to determine how much to slow your application down so that you can avoid getting out of memory. You are letting the framework determine if you can perform the operation and not taking a guess on how much you "think" you can get away with based on how much memory your app is using.

You should also check for memory usage through the garbage collector not the process to get an accurate reading of how much managed memory is actually allocated. Using private memory size will give you a much lower reading and you could still land up in an out of memory situation although it appears you have plenty to spare.

The code sample on the MSDN page shows how to estimate memory usage for an operation and to use that information to wait until memory is available before trying to process more requests. If you can determine the areas of code that have large memory requirements this is a good option to constrain it and avoid running out of memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!