Admiral Land Admiral Land - 25 days ago 7
C# Question

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?

rbm rbm
Answer

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.