Hossein Ebrahimi
Hossein Ebrahimi

Reputation: 822

Make a thread-safe list of integers

I need to make a class that stores a List of int and read/write from it asynchronously.

here's my class:

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

But it is not thread-safe until here. when I do multiple operations from different threads I get this error:

Collection was modified; enumeration operation may not execute.

What I missed here?

Upvotes: 0

Views: 94

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273419

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

But the performance won't be very good this way, and GetNumbers() now returns a snapshot copy.

Upvotes: 2

Related Questions