Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write copy-on-write list in .NET
    text
    copied!<p>How to write a thread-safe list using copy-on-write model in .NET?</p> <p>Below is my current implementation, but after lots of reading about threading, memory barriers, etc, I know that I need to be cautious when multi-threading without locks is involved. Could someone comment if this is the correct implementation?</p> <pre><code>class CopyOnWriteList { private List&lt;string&gt; list = new List&lt;string&gt;(); private object listLock = new object(); public void Add(string item) { lock (listLock) { list = new List&lt;string&gt;(list) { item }; } } public void Remove(string item) { lock (listLock) { var tmpList = new List&lt;string&gt;(list); tmpList.Remove(item); list = tmpList; } } public bool Contains(string item) { return list.Contains(item); } public string Get(int index) { return list[index]; } } </code></pre> <p><strong>EDIT</strong></p> <p>To be more specific: is above code thread safe, or should I add something more? Also, will all thread eventually see change in <code>list</code> reference? Or maybe I should add <code>volatile</code> keyword on list field or Thread.MemoryBarrier in Contains method between accessing reference and calling method on it?</p> <p>Here is for example <a href="http://developer.classpath.org/doc/java/util/concurrent/CopyOnWriteArrayList-source.html" rel="nofollow noreferrer">Java implementation</a>, looks like my above code, but is such approach also thread-safe in .NET?</p> <p>And <a href="https://stackoverflow.com/questions/11963972/in-java-can-i-depend-on-reference-assignment-being-atomic-to-implement-copy-on-w?rq=1">here</a> is the same question, but also in Java.</p> <p><a href="https://stackoverflow.com/questions/14921043/what-has-changed-in-the-memory-model-in-net-4-5">Here</a> is another question related to this one.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload