Intranoggin

Blither, Blather, Web Content Management.
Blog » Finally, I Have A Memory Leak

Finally, I Have A Memory Leak

With the announcement of a new release of SPDisposeCheck, I thought it might be a good time to repost this information about Response.Redirect and Server.Transfer.

If you execute a Response.Redirect (or Server.Transfer) inside a Try-Catch block, the Finally block will not execute.

So if you do this with objects that need disposed:

String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;
try
{
   oSPSite = new SPSite("http://server");
				
   oSPWeb = oSPSite.OpenWeb(..);
   str = oSPWeb.Title;
   if(bDoRedirection)
   {
       Response.Redirect("newpage.aspx");
   }
}
finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();
   if (oSPSite != null)
      oSPSite.Dispose();
}
You now have a memory leak.  Instead, you need to dispose of them explicitly before redirecting.
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");
   }
}
finally
			
{

				if (oSPWeb != null)
     oSPWeb.Dispose();

				if (oSPSite != null)
      oSPSite.Dispose();

}


Posted: 1/30/2009 8:45:00 AM by Ryan Miller | with 0 comments
Filed under: SharePoint