我需要创建一个存储 int 列表并异步读取/写入的类。
这是我的课:
public class ConcurrentIntegerList
{
private readonly object theLock = new object();
List<int> theNumbers = new List<int>();
public void AddNumber(int num)
{
lock (theLock)
{
theNumbers.Add(num);
}
}
public List<int> GetNumbers()
{
lock (theLock)
{
return theNumbers;
}
}
}
但直到这里它才不是线程安全的。当我从不同的线程执行多个操作时,我收到此错误:
Collection was modified; enumeration operation may not execute.
我在这里错过了什么?