如何正确的打开和关闭相关Object,如 SPSite, SPWeb 等,从而避免内存资源的浪费?

本文介绍了两种在SharePoint中释放资源的方法:一是利用using语句让系统自动处理资源回收;二是通过Try...Catch...Finally...结构手动关闭和清理资源。此外,还提到了使用SPControl.GetContextSite()获取SPSite实例时无需手动调用Dispose()方法,并给出了处理SPList.Items集合的高效建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 方法一:让系统自动帮你收回

 

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

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值