Note that there are some explanatory texts on larger screens.

plurals
  1. POC# ReaderWriterLockSlim Best Practice to Avoid Recursion
    text
    copied!<p>I have a class using <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" rel="noreferrer">ReaderWriterLockSlim</a> with a read method and a write method that uses the read method to retrieve the element to be modified. A quick example would be:</p> <pre><code>class FooLocker { ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); public void ChangeFoo(int index, string bar) { locker.EnterWriteLock(); try { Foo foo = GetFoo(index); foo.Bar = bar; } finally { locker.ExitWriteLock(); } } public Foo GetFoo(int index) { locker.EnterReadLock(); //throws System.Threading.LockRecursionException try { return fooList[index]; } finally { locker.ExitReadLock(); } } //snipped code for adding instances etc. } </code></pre> <p>As above, this code throws a <code>LockRecursionException</code> when calling <code>ChangeFoo()</code> because a write lock is already held when <code>GetFoo()</code> tries to enter a read lock.</p> <p>I've checked the documentation for <code>ReaderWriterLockSlim</code> and I can use <code>LockRecursionPolicy.SupportsRecursion</code> to allow the above to work. However, the documentation also recommends that this shouldn't be used for any new development and should only be used when upgrading existing code.</p> <p>Given this, what is the best practice to achieve the same result where a write method can use a read-only method to retrieve the thing that needs to be modified?</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