正确处置 SharePoint 对象?
-
03-07-2019 - |
题
我希望这里有一位 SharePoint 专家可以帮助解决这个问题。
问题就在这里。我的 SharePoint 日志多次包含此行:
An SPRequest object was not disposed before the end of this thread. To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it. This object will now be disposed. Allocation Id: {8D090AD2-5D55-42C2-9873-2D5486FE257C} To determine where this object was allocated, create a registry key at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings. Then create a new DWORD named SPRequestStackTrace with the value 1 under this key.
我编辑了注册表并添加了密钥,但找不到堆栈跟踪。它不在 SharePoint 日志或事件查看器中。
我确实需要找到这些 SPSite/SPWeb 泄漏的根源并修复它们,但我不能只是开始编辑可能是也可能不是问题根源的代码。有没有人有什么建议?
解决方案
您需要重新启动受影响的进程(如果是w3wp.exe重新启动IIS)以捕获注册表更改。
其他提示
到目前为止,检查处置警告的最佳位置是:
在您的情况下,OpenWeb()需要包含在使用中。如果你将它丢弃在你的fianlly块中,那么我建议显示更多的代码,看看你是否正在调用任何其他的“gotcha”。实例。此外,如果从SPContext类获取某些SPSite和SPWeb对象,则不必处置它们。
如果要跟踪对象的处理,可以继承它们,并覆盖onload和ondispose方法,以详细的消息传递方式记录它们。
读取代码表明SPWeb对象是在RunWithElevatedPriviledges委托之外声明的。这可能会影响SharePoint处理它们的方式。通常建议您对委托内的对象执行您需要执行的操作。
来自 http://msdn.microsoft.com/en-us /library/aa973248.aspx 上面提到过的链接:
调用 Response.Redirect将不会执行finally块。因此, 在进行任何重定向或转移处理之前,您必须进行处置 对象。
鉴于您的示例代码,您仍然可以生成无法处理的对象,因为Dispose()调用位于finally块中。
我的建议是将您的代码重新配置为以下内容:
try
{
//instantiate the SPSite and SPWeb with elevated privileges:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite mySite = new SPSite(url))
{
using (myWeb = mySite.OpenWeb())
{
//do stuff here
}
}
});
}
如果你有多个Using语句层,你可以像这样“堆叠”它们并减少代码缩进的数量(类似于if语句执行下一行或块的方式):
try
{
//instantiate the SPSite and SPWeb with elevated privileges:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite mySite = new SPSite(url))
using (myWeb = mySite.OpenWeb())
{
//do stuff here
}
});
}
我建议您阅读:
微软软件定义网络 : 最佳实践:使用 SharePoint 对象模型时的常见编码问题微软软件定义网络 : 最佳实践:使用一次性 Windows SharePoint Services 对象克里斯·奥布莱恩 : 处置 SharePoint 对象 - 他们没有告诉您什么
如果这些建议都不起作用。看一眼 对 WSS v3 和 MOSS 2007 中的 SPSite/SPWeb 泄漏进行故障排除.
编辑 :您应该处置 SPSite 对象。既然会 自动处理他的所有 SPWeb 对象.