If you’ve been in the SharePoint business for a while (at least a couple of days) you should be aware of the SharePoint objects that needs to be properly disposed; SPSite and SPWeb in particular. Objects that need disposal inherits from the IDisposable interface and requires that you call the Dispose() method when you’re done with the object - this is to ensure that the object frees up resources that the .NET managed garbage collector cannot free up automatically. This includes objects such as non-managed SQL connections, resource handles, file handles etc. Disposing objects is nothing unique for SharePoint - all (real) .NET developers know how to dispose of a SQL connection. You can read more about the best practices around disposing SharePoint objects in the MSDN Disposing Objects article. Not doing this properly will eventually lead to application crashes, high memory usage and/or bad performance.
The SPUserSolution object requires disposal
If you are working with sandboxed or user solutions in code you’ve probably used the SPUserSolution object. This is another of these objects that needs your disposal-attention. A solution package (farm or user code) is essentially a cabinet file (compressed file) containing all the solution artifacts and assemblies. When activating a user code solution programmatically in the solution gallery you will get this SPUserSolution object which internally will contain a number of stream objects (also inheriting from IDisposable) and a non-managed file handle. These object must be disposed manually to avoid any resource or memory leaks. Here is a proper way to add and activate a user code solution
byte[] bytes = ...;// grab the solution gallerySPDocumentLibrary solutions = (SPDocumentLibrary)newSite.GetCatalog(SPListTemplateType.SolutionCatalog);// add the solution to the gallerySPFile solutionFile = solutions.RootFolder.Files.Add("mysolution.wsp", bytes);// activate Solutionusing (SPUserSolution solution = newSite.Solutions.Add(solutionFile.Item.ID)) { // do your thing...}
Summary
This was just a sample and a reminder that you need to be aware of what’s happening when working with some of the SharePoint objects - make sure that you do your “Disposal dance” the correct way. The list goes long on what objects need to be disposed correctly - just check your objects if they inherit from IDisposable using Visual Studio or Reflector. Not all objects do any specific disposing though and some can be ignored - but better be safe than sorry.
Tip: products such as CodeRush from DevExpress has some great built-in tools to directly identify objects inheriting from IDisposable and helps you make sure that they are properly disposed.