Pergunta

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()

Foi útil?

Solução

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top