When to dispose of objects in SharePoint API
When developing against the SharePoint API we have many ways of obtaining object references to sites or site collections. We can use the “SPContext.Current.Site” to get our current site collection. We can use “SPSite siteColl= newSPSite(http://server)” to open a particular site collection. We can use “SPContext.Current.Web” to open the current site. We can use “SPWeb web = siteColl.OpenWeb()” to open a specific site on the site collection.
However, did you know you need to dispose of the objects some of the time, but not all of the time? SPWeb and SPSite implement IDisposable, so it would seem reasonable that we should dispose of them. On a side note: I recommend using “using” statements to dispose of objects (it is the easiest), but try catch blocks work also.
So, which ones do we need to Dispose of and which ones should we leave alone. The answer is anything that uses the current context should not be disposed of. Thus, “SPContext.Current.Web” should not be disposed of and “SPContext.Current.Site” should not be disposed of. However, the other statements (which are basically newing up the objects) should be disposed of every time. The reason is SharePoint keeps an internal list for everything in the “SPContext”. Then, when the page is completed it tries to dispose of all the objects in that list. If you have already disposed of these objects then things will break. However, if you new the object up yourself, it is not put into these internal lists and you will need to dispose of it or you will start getting log errors and warnings about too many SP objects open.
And, as one of my collegues at RDA (Deepak Gupta) recently pointed out to me, there is a commonly missed usage of this – loops.