Skip to main content

Phi Lieu's Library tagged Development   View Popular

14 Jan 09

Stefan Goßner : Disposing SPWeb and SPSite objects

What would happen if we would add code to dispose the SPWeb or SPSite object earlier? In some rare cases you will see an exception. But in most cases you would not see a problem with your code! Everything would work fine - but why?

The reason is that many methods silently recreate the SPWeb objects if it has been disposed. That means: even though you disposed the object in your code - a couple of code lines later it suddenly reappears and would have to be disposed again.

So the answer to the question is: You should dispose a SPWeb or SPSite object after the last access to a child object of this object. Be aware that a sub site (SPWeb) is not a child object. But (e.g.) a list or a folder or list item is a child object for this scenario.

blogs.technet.com/...-spweb-and-spsite-objects.aspx - Preview

SharePoint Development

  • What would happen if we would add code to dispose the SPWeb or SPSite object earlier? In some rare cases you will see an exception. But in most cases you would not see a problem with your code! Everything would work fine - but why?


    The reason is that many methods silently recreate the SPWeb objects if it has been disposed. That means: even though you disposed the object in your code - a couple of code lines later it suddenly reappears and would have to be disposed again.


    So the answer to the question is: You should dispose a SPWeb or SPSite object after the last access to a child object of this object. Be aware that a sub site (SPWeb) is not a child object. But (e.g.) a list or a folder or list item is a child object for this scenario.

  • Also please do not dispose the RootWeb property of SPContext.Current.Site. This object is used in many different places in SharePoint and you should not dispose it. It will automatically be cleaned up when the request finishes.
1 - 20 of 33 Next ›
Showing 20 items per page

Highlighter, Sticky notes, Tagging, Groups and Network: integrated suite dramatically boosting research productivity. Learn more »

Join Diigo