Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharePoint memory leak

Does this contain a memory leak? I've been trying to better understand memory leaks, but I can't tell if I have corrected this? If not, how do I correctly dispose of the SPweb object and SPSite object?

using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb()) //Open SP Web
{
    SPListCollection collList = oWebsite.Lists; //Open Lists

    foreach (SPList oList in collList)
    //For Each List Execute this
    {
        if (!oList.Hidden)
        //If the list is hidden do this else nothing
        {
            ListSitesDropDownBox.Items.Add(new ListItem(SPEncode.HtmlEncode(oList.Title), SPEncode.HtmlEncode(oList.Title)));
            ViewState["Item" + counter] = SPEncode.HtmlEncode(oList.Title);
            counter++;
        }
    }
}
like image 454
atrljoe Avatar asked Feb 23 '11 23:02

atrljoe


People also ask

Can memory leaks be fixed?

If you have a memory leak and get to the point of almost running out of memory, the normal procedure is to reboot the machine in order to clear out the memory. You can use RAMMap to clear areas of memory negating the need to reboot the machine.

How do I find a memory leak in SharePoint 2013?

If the SharePoint solution is already deployed on a server, the only way to detect a memory leak is to periodically check the amount of memory used by the services and applications. We can either employ Task Manager or any other process explorer within a server to measure the memory usage.

What is the main cause of memory leaks?

A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.


1 Answers

Yep, it does. You dispose of SPWeb but forget disposing of SPSite.
The right way to do this:

using (var site = new SPSite(webUrl))
using (var web = site.OpenWeb()) {
    // ...
}

Note that this is equivalent to:

using (var site = new SPSite(webUrl)) {
    using (var web = site.OpenWeb()) {
        // ...
    }
}

but I omitted braces for outer using to reduce code nesting. The bracing rules are the same as for if.

A few stylistic remarks:

  • Please, don't use Systems Hungarian in C# code. Just list.
  • Comments that rephrase the code above don't make any sense. Keep them constructive, i.e. explaining the purpose of the code. Instead of those four comments, you should've written something like that in the beginning:

    // Populate drop-down list with list names and save them in ViewState
    
like image 67
Dan Abramov Avatar answered Nov 10 '22 00:11

Dan Abramov