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++;
}
}
}
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.
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With