When you develop SharePoint solution using code, you need to Dispose SPWeb appropriately to avoid
memory Leaks. The general guideline for this are:
memory Leaks. The general guideline for this are:
Dispose | Not to dispose |
OpenWeb() AllWebs site.AllWebs | RootWeb
SPWeb from SPContext
|
Ensure that you only dispose SPSite and SPWeb objects that your code owns.
Examples that you don’t own(Which means you should not use Dispose() to clear the memory reference of
this objects)
- SPContext.Current.Web
- SPContext.Current.Site
- SPContext.Current.Site.RootWeb
Do not explicitly call Dispose() on the site.RootWeb property. The dispose cleanup will be handled automatically by the SharePoint and the .NET
framework. For existing SharePoint customization removal of explicit RootWeb Dispose is recommended to avoid an edge case condition where
the SPContext.Current.Web has equality to the SPSite.RootWeb. Problems can occur when disposing RootWeb when obtained from any variation
of SPContext (For Example: SPContext.Site.RootWeb, SPContext.Current.Site.RootWeb and GetContextSite
(Context).RootWeb ).
framework. For existing SharePoint customization removal of explicit RootWeb Dispose is recommended to avoid an edge case condition where
the SPContext.Current.Web has equality to the SPSite.RootWeb. Problems can occur when disposing RootWeb when obtained from any variation
of SPContext (For Example: SPContext.Site.RootWeb, SPContext.Current.Site.RootWeb and GetContextSite
(Context).RootWeb ).
In general, there are three common cases where you do own the object(You can dispose these objects):
- When you new up your own SPSite object:
SPSite site = new SPSite(url); // site.Dispose(); - When you explicitly call SPSite.OpenWeb():
SPWeb web = site.OpenWeb(url); // web.Dispose(); - When you iterate through SPSite.AllWebs – this is an extremely expensive operation, so avoid if possible:
foreach(SPWeb web in site.AllWebs) {
// …
web.Dispose();
} - Disposing the SPSite will close the associated SPWeb objects.
SPSite object is in effect.
No comments:
Post a Comment