SPWeb和SPSite这两个对象,虽然是托管的类,但里面使用了非托管的代码,针对托管代码的自动释放回收功能,是无法释放这部分资源的。因此,使用这两个对象是,必须使用手动的方式进行释放。由于其实现了IDisposable 接口,所以建议使用Dispose方法进行释放。
方法1:使用using
因为using语句,实际上是使用了try/finally块,并在finally块中自动调用IDisposable 接口的Dispose方法进行释放,因此相当于手动进行了释放。
String str;

using(SPSite oSPsite = new SPSite("http://server"))
{
  using(SPWeb oSPWeb = oSPSite.OpenWeb())
   {
       str = oSPWeb.Title;
       str = oSPWeb.Url;
   }

但要注意的是,如下代码只能释放SPWeb,而无法释放SPSite。
 New SPSite will be leaked.
    } // SPWeb object web.Dispose() automatically called.
}
 
方法2:使用try/catch/finally块
有时候,我们需要对异常进行处理,这是就需要使用try/catch/finally块的方法来释放SPWeb和SPSite这两个对象。如下例:
   oSPWeb = oSPSite.OpenWeb(..);

   str = oSPWeb.Title;
}
catch(Exception e)
{
   //Handle exception, log exception, etc.
}
finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();

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

如果在try中调用Response.Redirect 则需要注意了。有任何重定向或迁移执行,必须首先进行释放,如下例:
   }
}
catch(Exception e)
{
}
finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();

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

但是,在using中进行重定向或迁移却没有问题。

最后,需要说明的是,通过SPContext 类得到的SPSite和SPWeb,是不需要手动释放的,这是由于他们是由SharePoint框架来自行管理的。取得的方法一般是通过以下类取得:
      SPContext.Site, SPContext.Current.Site, SPContext.Web, 和SPContext.Current.Web

具体内容,可参照以下MSDN:
Best Practices: Using Disposable Windows SharePoint Services Objects.

相关文章: