代码之家  ›  专栏  ›  技术社区  ›  Jared Merritt

如何停止向列表中添加两个相同ID?(C#多线程)

  •  0
  • Jared Merritt  · 技术社区  · 8 年前

    我有一个问题可能很容易解决,但由于某种原因,我无法集中注意力。。。

    我有一个列表,其中包含一个包含一些信息的类。其中一个是ID,它从0开始,每次提交时增加一个。

    当运行多个线程时,它们会提交相同ID的不同变体。这应该是不可能的,因为它会在我真正调用列表之前检查是否可以添加它<>().添加

    有什么建议可以避免这种情况吗?

    主要方法:

    public static bool AddToList(List<ExampleItem> itemList, List<Xxx> xxx, ExampleItem newItem)
    {
        ExampleItem lastItem = itemList[itemList.Count - 1];
    
        // We must validate the old item one more time before we progress. This is to prevent duplicates.
        if(Validation.ValidateIntegrity(newItem, lastItem))
        {
            itemList.Add(newItem);
    
            return true;
        }
        else
            return false;
    }
    

    验证方法:

    public static bool ValidateBlockIntegrity(ExampleItem newItem, ExampleItem lastItem)
    {
        // We check to see if the ID is correct
        if (lastItem.id != newItem.id - 1)
        {
            Console.WriteLine("ERROR: Invalid ID. It has been rejected.");
            return false;
        }
        // If we made it this far, the item is valid.
        return true;
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Jared Merritt    8 年前

    感谢@mjwills和删除他们答案的人的建议,我找到了一个好方法。

    我现在用的是 ConcurrentDictionary<long, ExampleClass> 这意味着我可以索引和添加,而不必冒重复ID的风险——这正是我所需要的。