Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your approach looks correct, but I'd recommend using a <code>string[]</code> rather than a <code>List&lt;string&gt;</code> to hold your data. When you're adding an item, you know exactly how many items are going to be in the resulting collection, so you can create a new array of exactly the size required. When removing an item, you can grab a copy of the <code>list</code> reference and search it for your item before making a copy; if it turns out that the item doesn't exist, there's no need to remove it. If it does exist, you can create a new array of the exact required size, and copy to the new array all the items preceding or following the item to be removed.</p> <p>Another thing you might want to consider would be to use a <code>int[1]</code> as your lock flag, and use a pattern something like:</p> <pre><code>static string[] withAddedItem(string[] oldList, string dat) { string[] result = new string[oldList.Length+1]; Array.Copy(oldList, result, oldList.Length); return result; } int Add(string dat) // Returns index of newly-added item { string[] oldList, newList; if (listLock[0] == 0) { oldList = list; newList = withAddedItem(oldList, dat); if (System.Threading.Interlocked.CompareExchange(list, newList, oldList) == oldList) return newList.Length; } System.Threading.Interlocked.Increment(listLock[0]); lock (listLock) { do { oldList = list; newList = withAddedItem(oldList, dat); } while (System.Threading.Interlocked.CompareExchange(list, newList, oldList) != oldList); } System.Threading.Interlocked.Decrement(listLock[0]); return newList.Length; } </code></pre> <p>If there is no write contention, the <code>CompareExchange</code> will succeed without having to acquire a lock. If there is write contention, writes will be serialized by the lock. Note that the lock here is neither necessary nor sufficient to ensure correctness. Its purpose is to avoid thrashing in the event of write contention. It is possible that thread #1 might get past its first "if" test, and get task task-switched out while many other threads simultaneously try to write the list and start using the lock. If that occurs, thread #1 might then "surprise" the thread in the lock by performing its own <code>CompareExchange</code>. Such an action would result in the <code>lock</code>-holding thread having to waste time making a new array, but that situation should arise rarely enough that the occasional cost of an extra array copy shouldn't matter.</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