Sunday, May 13, 2007

Managing unmanaged memory

The title of this post might seem confusing. Garbage Collector (or GC) in .Net is designed to take care of managed memory only, so what do you do in a case where you have a managed object that itself takes very small amount of memory but allocates significant amount of unmanaged resources? In that case, GC will not be aware of the actual memory allocated by your application and therefore will not be able to optimize the collection of unused resources.

In .Net 2.0, a new feature has been introduced to take care of such an issue. Now it is possible to make the GC aware about the large amount of unmanaged resources that should be taken care of via GC.AddMemoryPressure. This method accepts a long bytesallocated and informs GC that there are x bytes to be taken care of while scheduling garbage collection. Ideal place to use this method can be the object constructor.

Since we are increasing the memory pressure on GC, so we have to release it too when the object is no longer required. This can be taken care of by using GC.RemoveMemoryPressure after the unmanaged resources have been released. Two points should be taken care of in this kind of a situation: first, you should always release the same amount of memory pressure as much as you have added, failing which might adversely affect the application performance and second, since we are dealing with unmanaged resources, your object must be implementing the IDisposable interface and use it to release the object deterministically.

kick it on

No comments: