Dois-je disposer SPWeb ou SPList?
-
16-10-2019 - |
Question
Je suis en train de faire un tas de choses avec un SPWeb et beaucoup SPLists. Si je web simplement disposer dans la section finally
serait Cédant tous SPLists que j'instancié? (BTW, je comprends le concept de using
, donc devrais-je mettre en œuvre à la place using
?)
La solution
objets SPList ne peuvent être jetés.
Autres conseils
I recommend installing and running this tool to check whether you are disposing your objects correctly: SPDisposeCheck
The rule is complicated, but in a nutshell, you should dispose of any object that you create yourself that implements the IDisposable interface.
In the context of SharePoint, this includes:
- Any SPSite object you create using
siteColl.OpenWeb()
, returned bySPSiteCollection.Add
, by theSPSiteCollection[]
index operator, or yielded in aSPSiteCollection
foreach
loop - Any SPWeb object returned from
SPSite.AllWebs.Add
,SPWebCollection.Add
, theSPSite.AllWebs[]
index operator or yielded in anSPSite.AllWebs
foreach loop.
There are many more cases outlined in the Best Practices: Using Disposable Windows SharePoint Service Objects article on TechNet.
Note that SPList is not in this list (because it does not implement IDisposable
, nor is SPList.RootWeb (because you don't create the RootWeb object, you just get a reference to it).
Note that your code is unlikely to compile if you try to Dispose
an object like SPList
that doesn't implement IDisposable
, because that object will not have a Dispose
method. On the other hand, you won't get an error if you try to dispose RootWeb
, because it is an SPWeb
object with a Dispose
method - but doing this will cause problems if you try to refer to that web or any of it's children later in your code.
The using
statement is a bit of syntactic sugar, but I prefer to use it because it ensures that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.