Monday, July 1, 2013

What,Why & How to resolve OutOfMemoryException in .Net

This is a normal exception happens in most of the .net applications. When ever developers see this they start thinking about the RAM of the system and divert their thoughts towards physical memory. But before going to that area there are some other things to be noted. 

What is OutOfMemoryException

  • An Exception in .Net which will be fired when the .net runtime is not able to allocate memory for object
  • The MSIL instructions such as newobj,newarr and box may throw this exception

Why OutOfMemoryException is occuring

  • Its not actually because there is not enough memory in the machine.(Memory shown in Task manager) 
  • Its because there is not enough continuous free memory in the process's address space to do memory allocation for objects

How to resolve

  • Facts before you try to solve this issue.
  • Steps for quick fix.
    • Convert the application to 64bit. This will remove the 2GB memory limit on process and largely increase the process address space so that there will be lesser fragmentation which provides more continuous free memory space.
  • Steps for actual fix
    • Use tools such WinDbg, .Net memory profiler etc... to find out the size of objects in the process memory. In most cases this will be very less than the memory shown in task manager.You may also use performance monitor counters to do the same.
    • If the size of objects and task manager reading has less difference ,it means you actually uses so many objects or the object you created are not deallocated properly. Check for memory leaks and fix it.
    • Check for LOH (Large Object Heap) fragmentation and fix it.
    • If you really want to work with huge objects use MemoryFailPoint class

No comments: