Wednesday, 7 September 2011

SPLimitedWebPartManager and the famous memory leak

When you program you always have to be aware of disposing the SPSite or SPWeb objects if you don’t want to cause a memory leak. Many people use Using(SPSite _site = ,,,) to avoid dealing with Dispose() so using will do it for them.
I am good friend of this practice, Dispose() brings me to the old C++ memory allocation. Using looks more sophisticated.

The original definition for SPLimitedWebPartManager  is this one: “Provides a limited set of Web Part operations that can be performed in object model scenarios when there is no HttpContext and no instantiated Page object.”

Beleive or not that means SPLimitedWebPartManager  will create its own SPWeb object inside, and we need to dispose that. How? I am going to attach two approaches for the same code

Approach 1:

using (SPLimitedWebPartManager _lLimitedWebPartManager= 
       defaultPage.GetLimitedWebPartManager(PersonalizationScope.Shared)) {

Approach 2:

SPLimitedWebPartManager _LimitedWebPartManager = defaultPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
if (_LimitedWebPartManager!=null) _LimitedWebPartManager.Web.Dispose();

No comments: