Question

Is it necessary to dispose the site and web objects in the following code? If so, how do I do this?

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim site As New SPSite(SPContext.Current.Web.Url)
    Dim web As SPWeb = site.OpenWeb()
    web.AllowUnsafeUpdates = True
    Dim lPmr As SPList = web.Lists("NombreList")
    Dim oQuery As New SPQuery()
    Dim itemCollectionPMR As SPListItemCollection

    oQuery = New SPQuery()
    oQuery.Query = ""
    itemCollectionPMR = lPmr.GetItems(oQuery)

 ........        

 End Sub
Was it helpful?

Solution

James and Toni are absolutely correct but have missed the obvious IMHO - your code has a deeper flaw and if you fixed this then disposing the objects is not required.

You should (where possible) use the SPWeb and SPSite objects from SPContext - they are already created for you by the SharePoint web part infrastructure and its more efficient to use these than create your own.

In your code you are actually already using one of them to get the current webs URL, but then creating your own site and web regardless - pretty inefficient and not necessary.

So instead of

Dim site As New SPSite(SPContext.Current.Web.Url)
Dim web As SPWeb = site.OpenWeb()

You should be using just

Dim web As SPWeb = SPContext.Current.Web

If you use SPSite/SPWeb from SPContext these rather than creating your own then you should NOT dispose of them (you didn't create them, so leave them alone)

See MSDN - Best Practices: Using Disposable Windows SharePoint Services Objects

SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

OTHER TIPS

Yes, you will need to dispose SPWebs created through SPSite.OpenWeb().

To dispose of it, simple call web.Dispose() when you're done in the method.

You could also use the Using statement to the same effect, without needing to directly call Dispose()

Using site As New SPSite(SPContext.Current.Web.Url)
  Using web As SPWeb = site.OpenWeb()
    web.AllowUnsafeUpdates = True
    Dim lPmr As SPList = web.Lists("NombreList")
    Dim oQuery As New SPQuery()
    Dim itemCollectionPMR As SPListItemCollection

    oQuery = New SPQuery()
    oQuery.Query = ""
    itemCollectionPMR = lPmr.GetItems(oQuery)
  End Using
End Using

+1 James

You should also try to use SharePoint Dispose Checker tool in your projects to analyze your code for potential memory leaks and to apply best practices.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top