【问题标题】:How to stop adding two of the same ID to a list? (C# Multithreading)如何停止将两个相同的 ID 添加到列表中? (C# 多线程)
【发布时间】:2019-01-16 11:08:45
【问题描述】:

我遇到了一个可能很容易解决的问题,但由于某种原因我无法解决问题......

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

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

关于如何避免这种情况的任何建议?

主要方法:

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;
}

【问题讨论】:

  • List&lt;T&gt; 不是线程安全的。以任何方式这样做都是不安全的。如果你真的想使用List&lt;T&gt;,那么你需要一个lock 来围绕它的所有读/写。
  • 您可能想要使用并发哈希集 - stackoverflow.com/questions/18922985/…
  • One of these is an ID, which starts from 0 and increases by one with each submission. 还可以考虑使用Interlocked.Increment 进行线程安全的 int 生成。

标签: c# multithreading concurrency multiprocessing


【解决方案1】:

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

我现在使用的是ConcurrentDictionary&lt;long, ExampleClass&gt;,这意味着我可以同时索引和添加,而不会冒重复 ID 的风险——这正是我所需要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-09
    • 2018-03-10
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2015-03-21
    相关资源
    最近更新 更多