heinzbeinz heinzbeinz - 3 months ago 21
C# Question

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
.

Answer

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);
            // ...
        }
    }
}
Comments