Search code examples
c#collectionspropertiesthread-safety

Thread-safe List<T> property


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?


Solution

  • 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>