我有一个问题可能很容易解决,但由于某种原因,我无法集中注意力。。。
我有一个列表,其中包含一个包含一些信息的类。其中一个是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;
}