Admiral Land
Admiral Land

Reputation: 2492

How to create a custom thread-safe IList<T>?

I have a question about the lock operator:

For example, I have a custom thread-safe (I hope) list:

public class BlockingList<StateMessage> : IList<StateMessage>
{
    private List<StateMessage> _list = new List<StateMessage>();
    private object _sync = new object();


    public void Add(StateMessage item)
    {
        lock (_sync)
            _list.Add(item);
    }

    public bool Remove(StateMessage item)
    {
        lock (_sync)
        {
            return _list.Remove(item);
        }
    }

    public void Clear()
    {
        lock (_sync)
            _list.Clear();
    }
}

So, if the first thread adds an element, but a second one calls the Clear() method at the same time, would it be thread-safe?

Upvotes: 0

Views: 196

Answers (1)

rbm
rbm

Reputation: 3253

Yes, your code is thread-safe since the methods are first locking or waiting to lock the _sync object.

You could use ConcurrengBag if you don't want to write your own. While it does not have the Clear method, you could simply create a new instance of ConcurrentBag and replace the old one.

Upvotes: 2

Related Questions