Будет использование объекта «Splist», полученное из распоряженного «.OpenWeb (), вызывающих ошибки?

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/54486

  •  10-12-2019
  •  | 
  •  

Вопрос

использует объект SPList, полученный из распоряженного генеракодицетагкода, вызывает ошибки?

SPList list = null;

using (SPWeb web = SPContext.Current.Site.OpenWeb("/myweb")){
    list = web.Lists["Awesome Name"];
}

SPListItemCollection items = list.Items;
.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top