How to properly dispose of SP objects although not assigned?
If I assign SPContext.Current.Site.OpenWeb(开发者_高级运维).Title
to a string, do I need to dispose of it (if possible)?
string title = SPContext.Current.Site.OpenWeb().Title;
I'm still a little fuzzy on when to dispose of sp objects, so I always dispose of my SPWeb
and SPSite
objects... But, if I don't assign the statement above to an object first, is there any disposing I need to do? I also understand that there are certain cases where using Current eliminates the need to dispose.
Thanks.
Actually this is an edge case where the dispose is redundant. It's not going to cause any problems so there's no harm to getting in the habit, so you could leave it there for the moment. It's redundant because any webs opening using openweb will be automatically disposed of when the owning spsite is disposed. The context site is not owned by you, so it will be disposed by sharepoint at some point in the future, along with all webs opened via openweb.
disbelievers: take a look at the openweb code in reflector to verify.
Generally speaking, it doesn't matter whether you save the reference or not - OpenWeb
creates a new SPWeb
object in memory, and it should be disposed. That is true for all IDisposable
objects, not just in SharePoint - it isn't the reference that makes a difference, or the garbage collector could free that memory.
You should change your code to:
string title = null;
using(SPWeb web = SPContext.Current.Site.OpenWeb())
{
title = web.Title;
}
In theory, had you created a new SPSite
you should have disposed of it as well, but not when it comes from SPContext.Current
- these objects may be shared with other components.
In addition to Kobi's answer, please read Best Practices: Using Disposable Windows SharePoint Services Objects from Microsoft. Also, be sure to automatically check your code using Microsoft's SharePoint Dispose Checker Tool.
精彩评论