1

SPLimitedWebPartManager references SPWeb object internally and implements IDisposable interface, therefore we need to dispose it explicitly.

As I understand, we need to dispose its internal SPweb object like this: SPLimitedWebPartManager.Web.Dispose(); But I also see some code in many places where it calling dispose method directly on SPLimitedWebPartManager.Dispose(); So, whats the difference on calling between SPLimitedWebPartManager.Web.Dispose(); vs SPLimitedWebPartManager.Dispose();

Fof example this code, how i dispose ?

SPLimitedWebPartManager mgr = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
try
   {
                foreach (var wp in mgr.WebParts)
                {
// i do some stuff here
                }
    }
catch { }
            finally
            {
               mgr.Dispose();// for disposing, this should be used
               mgr.Web.Dispose();// OR this ?
            }

Disposechecker has following comments for this line mgr.Dispose();

Dispose Explicitly Called on SPLimitedWebPartManager.Web mgr.{Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager}Dispose()

2

Calling SPLimitedWebPartManager.Web.Dispose() will dispose of the SPWeb object used by SPLimitedWebPartManager while calling SPLimitedWebPartManager.Dispose() would dispose the SPLimitedWebPartManager itself.

Keep in mind that you should never dispose of objects you haven't created yourself! SPLimitedWebPartManager.Web is created by another object called WebPartManager. Doing SPLimitedWebPartManager.Web.Dispose() is something similar to dividing by zero :)

Here is an example:

using (SPLimitedWebPartManager mgr = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared));
{
    foreach (var wp in mgr.WebParts)
    {
        //try-catch exceptions here if needed
        // i do some stuff here
    }
}

which basically compiles to:

SPLimitedWebPartManager mgr = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
try
{
    foreach (var wp in mgr.WebParts)
    {
        // i do some stuff here
    }
}
catch { }
finally
{
   mgr.Dispose();// for disposing, this should be used
}

Do not call mgr.Web.Dispose(); as this object will be disposed automatically by SPLimitedWebPartManager (or maybe WebPartManager).

  • I have edited my question by adding some code, let me know your thoughts how i dispose that? – SPBeginer Feb 8 '16 at 15:17
  • Thanks!! That means if i use SPLimitedWebPartManager within Using Directive, then I don't need to call Dispose method explicitly, right? – SPBeginer Feb 8 '16 at 15:37
  • That is exactly the point of "using" :) – Paul Strupeikis Feb 8 '16 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.