Thursday, July 31, 2008

Disposing SharePoint site and web objects

There are several different ways of retrieving an SPWeb object.

Take the following 3 examples:

1) SPContext
SPWeb web = SPContext.Current.Web

2) OpenWeb
SPSite site = new Site("http://myserver/");
SPWeb web = site.OpenWeb("");

3) Site "RootWeb"
SPSite site = new Site("http://myserver/");
SPWeb web = site.RootWeb;

Thumb rule:

  • Never dispose SPContext.Current.Web or SPSite.RootWeb
  • Make sure you dispose of [OpenWeb("")] objects and [new Site("")/new Web("")] objects
SPContext is in use by all resident controls and parts on the site and the page. If you dispose of the SPContext.Current.Web object then you will find that you get a nasty error message next time you try to access that object (forcing you to refresh the page). So if you've ever seen the error message below, check your disposal!
As for
[OpenWeb("")] and [new Site("")/new Web("")]objects, if not disposed, applies heavy penalty on system memory.

Hope this helps.


No comments: