加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – HashSet.Contains()对大型列表,多线程有效吗?

发布时间:2020-12-16 01:56:24 所属栏目:百科 来源:网络整理
导读:我正在编写一个多线程程序来刮取某个站点并收集ID.它将这些ID存储在共享静态List string中.宾语. 当任何项目添加到List string时,首先根据HashSet string检查它.其中包含已收集ID的黑名单. 我这样做如下: private static HashSetstring Blacklist = new Has
我正在编写一个多线程程序来刮取某个站点并收集ID.它将这些ID存储在共享静态List< string>中.宾语.

当任何项目添加到List< string>时,首先根据HashSet< string>检查它.其中包含已收集ID的黑名单.

我这样做如下:

private static HashSet<string> Blacklist = new HashSet<string>();
private static List<string> IDList = new List<string>();

public static void AddIDToIDList(string ID)
{
    lock (IDList)
    {
        if (IsIDBlacklisted(ID))
            return;
        IDList.Add(ID);
    }
}
public static bool IsIDBlacklisted(string ID)
{
    lock (Blacklist)
    {
        if (Blacklist.Contains(ID))
            return true;
    }
    return false;
 }

黑名单在完成后保存到文件中,并在每次程序启动时加载,因此,随着时间的推移它将变得非常大(最多50k记录).是否有更有效的方法来不仅存储此黑名单,还要检查每个ID?

谢谢!

解决方法

要提高性能,请尝试使用 ConcurrentBag<T>集合.此外,没有必要锁定BlackList,因为它没有被修改,例如:

private static HashSet<string> Blacklist = new HashSet<string>();
private static ConcurrentBag<string> IDList = new ConcurrentBag<string>();

public static void AddIDToIDList(string ID)
{
    if (Blacklist.Contains(ID))
    {
        return;
    }

    IDList.Add(ID);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读