Monthly Archives: March 2008

Beware of the SharePoint Memory Leaks!

Beware of the SharePoint Memory Leaks!

You might not know it, but when developing for SharePoint (either WSS 3.0 or MOSS 2007) it is very easy to cause memory leaks, which can ultimately thrash your SharePoint server’s performance. The reason for this is that even though your own code might be written using only managed code, the SharePoint API still uses unmanaged code in some places. These unmanaged resources have to be explicitly disposed of, especially considering the fact they are living inside an ASP.Net web application (SharePoint) and potentially can have a long lifetime.

The problem is that the SharePoint API doesn’t always make clear when exactly you have to dispose of objects explicitly. Sometimes it may look like you’re just inspecting a value of a property, while in the background a whole new object is instantiated, which holds valuable unmanaged resources that should be freed by the caller (you!). Other times you might find yourself disposing an object, only to find out you weren’t supposed to…

Way back in June 2006 Microsoft employees Scott Harris and Mike Ammerlaan released their article Best Practices: Using Disposable Windows SharePoint Services Objects on MSDN, which can be regarded as the mother of all articles on this subject. I think this article is often overlooked and should be considered essential reading material for every serious SharePoint developer out there. Also read their more recent article called Best Practices: Common Coding Issues When Using the SharePoint Object Model, which also handles topics like data and object caching and writing scalable code.

Recently two other Microsoft employees also wrote interesting pieces on this subject. Stefan Goßner did a piece called Dealing with Memory Pressure problems in MOSS/WSS, in which he explains what a "Memory Pressure Situation" is and he lists some common causes and solutions for it. The other interesting read came from Roger Lamb. His entry is called SharePoint 2007 and WSS 3.0 Dispose Patterns by Example and in it he shows some very clear code samples and patterns on how to properly handle SharePoint objects.

Very cool material, guys!