Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# parallel read access to List without copying

Consider the following example:

class Example
{
    private readonly List<string> _list = new List<string>();
    private readonly object _lock = new object();

    public IReadOnlyList<string> Contents
    {
        get
        {
            lock (_lock)
            {
                return new List<string>(_list);
            }
        }
    }

    public void ModifyOperation(string example)
    {
        lock (_lock)
        {
            // ...
            _list.Add(example);
            // ...
        }
    }
}

How could parallel read access to the Contents List be achieved without copying the whole List? In C# there are concurrent Collections, but there is no thread safe List. In Java there is something like the CopyOnWriteArrayList.

like image 836
Nico Avatar asked Aug 09 '16 10:08

Nico


1 Answers

In my opinion the ImmutableList<T> class from System.Collections.Immutable package is perfect for such scenario. It implements IReadOnlyList<T>, and since it's immutable, i.e. never modified, you can directly return it from the read accessor. The only synchronization needed will be between the modifying operations:

class Example
{
    private ImmutableList<string> _list = ImmutableList<string>.Empty;
    private readonly object _lock = new object();

    public IReadOnlyList<string> Contents => _list;

    public void ModifyOperation(string example)
    {
        lock (_lock)
        {
            // ...
            _list = _list.Add(example);
            // ...
        }
    }
}
like image 170
Ivan Stoev Avatar answered Oct 14 '22 05:10

Ivan Stoev