请考虑以下示例:
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);
// ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何Contents在不复制整个List的情况下实现对List的并行读访问?在C#中有并发Collections,但没有线程安全List.在Java中有类似的东西CopyOnWriteArrayList.