Skip navigation

Category Archives: development

.Net has some known issues with garbage collection and SharePoint has inherited those problems. When you create SPWeb objects (references to SharePoint sites) it does not automatically dispose of the object because (among other reasons) it does not know if you are finished using it.

SPDisposeCheck is an incredibly useful tool which will analyze your custom SharePoint assemblies (compiled dll files) for memory leaks in the form of poorly handled SPWeb objects (very common issue!). Some of my company’s externally developed SharePoint applications were causing server wide SharePoint issues (memory leaks, poor server performance) which sparked the investigation. I was able to find most of the memory leaks just browsing through their code but SPDisposeCheck did it in seconds versus manually searching through thousands of lines of code and even flagged some bad coding practices that I did not spot. It does not fix the code for you but it does tell you the exact file, method, line of code and bad pattern detected so you can easily fix it. Most cases can be resolved with a simple using statement around SPWeb objects so that they are automatically released at the end of the code block but there are three options for disposing:

  1. Wrap the new SPWeb object (“SPWeb web = new SPWeb(SPSite.OpenWeb())”) in a using statement
  2. Use a try, catch, finally and call SPWeb.Dispose() in the finally block
  3. Explicitly call SPWeb.Dispose() every time you’re finished with the object

Option #1 is usually my choice, but each have their use cases.

Note: You do need to use caution when disposing of objects that are called using SPContext (versus “newing up” a SPWeb object… “SPWeb web = new SPWeb()”) because objects created from SPContext are actually managed by SharePoint very well and if you dispose of it, the server will freak out when it tries to dispose of it. You won’t get memory leaks but your users will get nasty errors like Exception occurred. (Exception from HRESULT: 0×80020009 (DISP_E_EXCEPTION)) if not handled properly.

There is a great blog post that analyzes the patterns and shows how to prevent the memory leak in each case.

A great idea would be to configure SPDisposeCheck to automatically run as part of your Visual Studio build process and/or prior to being checked in to a code repository.

This is something that should be kept in mind when working with third party SharePoint developers and when developing solutions in house. It’s easy to miss these bugs but they can cause some serious problems for your SharePoint environment. Nothing should be deployed to production server until SPDisposeCheck returns a happy report on your custom assemblies.

Follow

Get every new post delivered to your Inbox.