Expand Minimize

Dispose SPWeb created by SPWebCollection[] index operator

The SPSite.AllWebs[] and SPWebCollection[] index operator returns a new SPWeb instance each time it is accessed. An object is created during the indexing operation even if that object was already accessed.

CheckId SPC110214
TypeName DisposeSPWebCreatedBySPWebCollectionIndex
Severity CriticalWarning
Type Assembly

The SPSite.AllWebs [] and SPWebCollection[] index operator returns a new SPWeb instance each time it is accessed. An object is created during the indexing operation even if that object was already accessed. If not properly closed, the following code samples leave an SPWeb object in the .NET Framework garbage collector. See sample from MSDN:
Bad Practice

void AllWebsForEachLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb outerWeb = siteCollection.OpenWeb())
    {
      foreach (SPWeb innerWeb in siteCollection.AllWebs)
      {
         // Explicitly dispose here to avoid out of memory leaks with large number of SPWeb objects.
      }
    } // SPWeb object outerWeb.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Good Practice
void AllWebsForEachNoLeakOrMemoryOOM()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb outerWeb = siteCollection.OpenWeb())
    {
      foreach (SPWeb innerWeb in siteCollection.AllWebs)
      {
        try
        {
          // ...
        }
        finally
        {
          if(innerWeb != null)
            innerWeb.Dispose();
        }
      }
    } // SPWeb object outerWeb.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Rule relates to SPDisposeCheckId 'SPDisposeCheckID_130'. To ignore this rule add the attribute '[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_130, "Caller will dispose")]' to your method.

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.MemoryDisposalGroup", "SPC110214:DisposeSPWebCreatedBySPWebCollectionIndex", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.