0

我需要创建一个存储 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.

我在这里错过了什么?

4

1 回答 1

2
public List<int> GetNumbers()
{
    lock (theLock)
    {
      // return theNumbers;
         return theNumbers.ToList();
    }
}

但是这种方式性能不会很好,GetNumbers() 现在返回一个快照副本。

于 2020-06-30T12:06:28.910 回答