方法一:让系统自动帮你收回
using(SPSite site = new SPSite("http://moss")
{
using (SPWeb web = site.OpenWeb());
{
// … do stuff with web
} // SPWeb object web.Close(), web.Displose() automatically called
} // SPSite object, site.Close(), site.Displose() automatically called
方法二:使用Try ... Catch... Finally... 自行处理
SPSite site = null;
SPWeb web = null;
try
{
site = new SPSite("http://moss");
web = site.OpenWeb();
// … do stuff with web
}
finally
{
if (null != web)
{
web.Close();
web.Dispose();
}
if (null != site)
{
site.Close();
site.Dispose();
}
}
另外,如果你使用 SPControl.GetContextSite() 来取得对应的 SPSite,则不需要再调用 Dispose() 方法进行清除,因为 SharePoint 将自动处理。
故以下方法是不合适的:
Don’t do using(SPSite site = SPControl.GetContextSite(this.Context)) {} Or SPSite site = SPControl.GetContextSite(this.Context); site.Dispose(); 此外,对SPList.Items ,需要避免在 Foreach 中使用,要使用它最好先将其赋值给一个变更,然后再对此变更使用 Foreach。如此可提高效率也可避免过多的内存耗用。 // Example of what not to do foreach (SPListItem item in SPList.Items) { // code to perform a task } // Example of what to do SPListItemCollection spItems = SPControl.GetContextSite(this.Context); foreach (SPListItem item in spItems) { // code to perform a task }