Quantcast
Channel: SharePoint 2010 - Development and Programming forum
Viewing all articles
Browse latest Browse all 11571

Dispose or not dispose SPWeb object??

$
0
0

Hey everyone,

currently we have some performance problems in our production SharePoint farm. The ULS logs the error "Attempt to read or write protected memomy. This is often an indication that other memory is corrupt." Well, f*** :)

So I downloaded the Microsoft dispose checker to check if there are any problems with the apps we developed for the SharePoint. Actually the tool found a problem:

we have a feature which replaces the default v4.master with our custom masterpage. The dispose checker found a problem in the FeatureActivated method. Here is the code:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
      {
          try
          {
              SPWeb rootWeb;
              String serverRelativeUrl;
              String fullmasterpageUrl;

              object objWeb = properties.Feature.Parent;
              if (properties.Feature.Parent is SPWeb)
              {
                  rootWeb = (SPWeb)objWeb;
              }
              else
              {
                  rootWeb = ((SPSite)objWeb).RootWeb;
              }

              serverRelativeUrl = rootWeb.ServerRelativeUrl;
              serverRelativeUrl = serverRelativeUrl.EndsWith("/") ? serverRelativeUrl : serverRelativeUrl + "/";

              fullmasterpageUrl = serverRelativeUrl + "_catalogs/masterpage/" + MasterPageFile;

              setMasterpage(rootWeb, fullmasterpageUrl);
          }
          catch (Exception ex)
          {
              // exception handling
          }
      }

private void setMasterpage(SPWeb web, String masterUrl)
      {
          try
          {
              SPWebCollection subwebs = web.Webs;

              if (subwebs.Count != 0)
              {
                  foreach (SPWeb subweb in subwebs)
                  {
                      setMasterpage(subweb, masterUrl);
                  }
              }

              web.MasterUrl = masterUrl;
              web.CustomMasterUrl = masterUrl;

              web.Update();
              web.Dispose();
          }
          catch (Exception ex)
          {
              // exception handling
          }
      }

When I do not dispose the rootWeb in the FeatureActicvated method, the dispose checker tells me to dispose it with the hint "This may be a false positive depending on how the type was created or if it is disposed outside the current scope". Wenn I dispose the rootWeb the dispose checker tells me not to dispose the object.

So... do I need to dispose the object or not??

Thank you for your answers :)


Viewing all articles
Browse latest Browse all 11571

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>