SPWeb and SPSite should be disposed of properly after usage in any of the following methods. Why?
- Frequent recycles of the Microsoft Windows SharePoint Services application pool, especially during peak usage
- Application crashes that appear as heap corruption in the debugger
- High memory use for Microsoft Internet Information Services (IIS) worker processes
- Poor system and application performance
I like the using method best...
// Example of disposal using "using"...
String str;
using(SPSite oSPsite = new SPSite("http://server"))
{
using(SPWeb oSPWeb = oSPSite.OpenWeb())
{
str = oSPWeb.Title;
str = oSPWeb.Url;
}
}
// Example using "try/catch/finally"...
String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;
try
{
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);
str = oSPWeb.Title;
if(bDoRedirection)
{
if (oSPWeb != null)
oSPWeb.Dispose();
if (oSPSite != null)
oSPSite.Dispose();
Response.Redirect("newpage.aspx");
}
}
catch(Exception e)
{
}
finally
{
if (oSPWeb != null)
oSPWeb.Dispose();
if (oSPSite != null)
oSPSite.Dispose();
}
*Any other object that creates/returns a SPWeb or SPSite object should be disposed of as well.