foreach循环在SharePoint 2010中耗时太长

时间:2013-02-14 11:24:47

标签: performance sharepoint collections foreach

我正在尝试从SharePoint 2010检索同义词,我的代码存在以下问题:它循环遍历没有索引器的keywordCollection。执行foreach需要太长时间,因为实例化一个新关键字持续大约5-10毫秒,到目前为止大约有8000个关键字,完成需要大约80秒。 到目前为止我尝试过的事情:

  • 获取枚举器 - >还需要80秒

  • 将集合转换为列表 - >失败的原因不明。

代码示例:

KeywordContext keywordContext = fastProxy.KeywordContext;
SearchSettingGroupCollection searchSettingGroupCollection = keywordContext.SearchSettingGroups;

foreach (SearchSettingGroup searchSettingGroup in searchSettingGroupCollection)
{
    if (searchSettingGroup.Name == siteId.ToString())
    {
        foreach (Keyword keyword in searchSettingGroup.Keywords)
        {
            //the rest of the work here, per total takes about 470ms
        }
    }
}

有没有办法在不使用foreach语句的情况下遍历集合,每次都会实例化一个新的object<T>

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

using (var site = new SPSite(siteCollectionUrl))
{
    // get the site ID
    var guid = site.ID.ToString();

    // code to get the fastProxy FASTAdminProxy

    KeywordContext keywordContext = fastProxy.KeywordContext;
    var ssgs = keywordContext.SearchSettingGroups;
    if (ssgs.ContainsSearchSettingGroup(guid))
    {
        var searchSettingGroup = ssgs.GetSearchSettingGroup(guid);
        foreach (var keyWord in searchSettingGroup.Keywords)
        {
            // do stuff with keyWord.Synonyms
        }
    }
}

此外,虽然我目前无法测试,但您可以尝试使用Parallel类:

using System.Threading.Tasks;

// ...

Keyword[] array = new Keyword[searchSettingGroup.Keywords.Count];
searchSettingGroup.Keywords.CopyTo(array, 0);
Parallel.ForEach<Keyword>(array, keyword =>
{
    //do stuff here
});