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
.
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);
// ...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With