Thread-safe List<T> property

Xaqron picture Xaqron · May 3, 2011 · Viewed 202.9k times · Source

I want an implementation of List<T> as a property which can be used thread-safely without any doubt.

Something like this:

private List<T> _list;

private List<T> MyT
{
    get { // return a copy of _list; }
    set { _list = value; }
}

It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.

How to implement a thread-safe collection property?

Answer

Bala R picture Bala R · May 3, 2011

If you are targetting .Net 4 there are a few options in System.Collections.Concurrent Namespace

You could use ConcurrentBag<T> in this case instead of List<T>