【发布时间】: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<T>不是线程安全的。以任何方式这样做都是不安全的。如果你真的想使用List<T>,那么你需要一个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