Will using a `SPList` object derived from a disposed `.OpenWeb()` cause errors?
Question
Will using a SPList
object derived from a disposed .OpenWeb()
cause errors?
SPList list = null;
using (SPWeb web = SPContext.Current.Site.OpenWeb("/myweb")){
list = web.Lists["Awesome Name"];
}
SPListItemCollection items = list.Items;
Solution
No, there will not be an error. I commonly use this design pattern to keep my using
blocks small.
SPList list;
using (SPWeb web = SPContext.Current.Site.OpenWeb("myweb"))
{
list = web.GetList("/myweb/Lists/Awesome Name");
}
SPListItemCollection items = list.Items;
If you are updating an SPListItem
in a manner that requires SPWeb.AllowUnsafeUpdates = true;
though, you will need to maintain the reference to the SPWeb
(IE: do all the work in the using
block.)
For more information about when you would need to set the AllowUnsafeUpdates
property, see Hristo Pavlov's What you need to know about AllowUnsafeUpdates. It's the best explanation I've found about it.
I do this a lot so I don't have so many nested blocks in my code. It makes it a lot cleaner. Once you retrieve a list it's stored in memory. The same is true if you use the list only within your using
block. If something gets changed between the time you load the list and the time you request a value (from an item for instance), the value you get is the value that was present when you loaded the list in the first place.
This is also why if you're only getting a couple lists you should use SPWeb.GetList()
instead of SPWeb.Lists[index]
. SPWeb.Lists
loads all lists in the web on the first call. GetList()
makes a database call each time, but if there are a lot of lists in the web you're loading a lot less into memory. It's a trade off.