Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would fully <em>expect</em> the write-lock to function as a memory barrier (within the write-lock, in particular), but I can't prove it off-hand.</p> <p>Whether you need the complexity of <code>ReaderWriterLockSlim</code> depends on the context; <code>Interlocked</code>, <code>volatile</code>, <code>lock</code> or <code>[MethodImpl]</code> might each do the job far more simply. You mainly need <code>ReaderWriterLock[Slim]</code> if you have lots of readers and few writers.</p> <p>However, the <code>get</code> is not currently protected by the lock; you'll need to us an explicit property implementation and take out a read lock yourself if you ever need multiple operations to be spanned by the write-lock (without readers seeing intermediate values).</p> <p>As an aside, the <code>Count++</code> usage would probably be more familiar to people.</p> <p>You should also use <code>try</code>/<code>finally</code> to ensure you release the lock on exception.</p> <p>To avoid the issue of taking write then read locks, perhaps:</p> <pre><code> private ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(); private int count; public int Count { get { rwLock.EnterReadLock(); int tmp = count; rwLock.ExitReadLock(); return tmp; } } public void Add(object x) { rwLock.EnterWriteLock(); try { // do some processing count++; } finally { rwLock.ExitWriteLock(); } } </code></pre> <hr> <p>Updated re your edit;</p> <p>That looks pretty solid. A <code>List&lt;T&gt;</code> would be my recommendation (over a <code>T[]</code> array), since it will do all the doubling etc internally, saving you lots of code. Since only one thread can update <code>Count</code> at a time, there is no need for <code>Interlocked</code>, and this property saves the need for a lock when reading <code>Count</code>, as long as you're fine for callers to get the old <code>Count</code> while another thread is adding rows (rather than being blocked).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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