Cook Computing

AddMemoryPressure

November 18, 2004 Written by Charles Cook

Avnrao's Blog has a post GC on small managed resource holding large unmanaged resources... By default small objects will have a low priority as far as GC is concerned but in Whidbey onwards you can boost this by calling GC.AddMemoryPressure. You may want to do this if the small object is holding onto a large unmanaged resource.

Brad Abrams has a post on this with some code:


class Bitmap {

   private long _size;

   Bitmap (string path ) {
      _size = new FileInfo(path).Length;
      GC.AddMemoryPressure(_size);
      // other work
   }

   ~Bitmap() {
      GC.RemoveMemoryPressure(_size);
         // other work
   }
}

And Miguel posted to the Mono-devel list about the problem being addressed:

The problem is that the memory consumption happens in unmanaged world, so the GC has no way of knowing that your very few allocations that you have performed each one has a big impact.

For example, say that the Pixbuf takes 32 bytes of RAM, but the actual data pointed to takes 6 megabytes. If you allocate 256 of these objects, as far as the GC is concerned, you have barely allocated 8k of GC memory, so it is not worth doing a collection for that little memory.

You should use the explicit Dispose method of Pixbuf in these cases (since you are using an unmanaged resource that the managed world has no idea what it is).