0

I've got an issue which is probably easily solvable, but for some reason I can't wrap my head around...

I have a single list, which contains a class which contains some information. One of these is an ID, which starts from 0 and increases by one with each submission.

When running multiple threads, they submit a different variation of the same ID. This should not be possible, as it checks whether it can be added just before I literally call the List<>().Add.

Any suggestions on how I can avoid this?

Main method:

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

Validation method:

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;
}
  • 2
    `List` is not thread-safe. This is not safe to do in any way. If you really want to use `List` then you will need a `lock` around all reads / writes to it. – mjwills Aug 09 '18 at 05:23
  • 2
    You likely want to use a Concurrent HashSet - https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework . – mjwills Aug 09 '18 at 05:24
  • 2
    `One of these is an ID, which starts from 0 and increases by one with each submission.` Also consider using `Interlocked.Increment` for thread-safe int generation. – mjwills Aug 09 '18 at 05:34

1 Answers1

1

Thanks for the suggestions from @mjwills and whoever deleted their answer, I was able to figure out a good method.

I'm now using a ConcurrentDictionary<long, ExampleClass> which means I can both index and add without risking the issue of having duplicated ID's - exactly what I needed.