Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you only have 2 threads accessing this resource (ie concurrent reads are not required), then the simplest (and one of the quickest) would just be to use the <code>lock</code> keyword:</p> <pre><code>public class QuoteStore { private readonly List&lt;Quote&gt; _quotes = new List&lt;Quote&gt;(); private readonly object _mutex = new object(); public ReadOnlyCollection&lt;Quote&gt; GetQuotes() { lock (_mutex) { return _quotes.ToReadOnly(); } } public void AddQuote() { lock (_mutex) { _quotes.Add(quote); } } } </code></pre> <p>If however concurrent reads are required this would be a good fit for <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" rel="nofollow">the ReaderWriterLockSlim class</a>. You can acquire the read lock when copying data and the write lock when writing data eg:</p> <pre><code>public class QuoteStore : IDisposable { private readonly ReaderWriterLockSlim _mutex = new ReaderWriterLockSlim(); private readonly List&lt;Quote&gt; _quotes = new List&lt;Quote&gt;(); public ReadOnlyCollection&lt;Quote&gt; GetQuotes() { _mutex.EnterReadLock(); try { return _quotes.ToReadOnly(); } finally { _mutex.ExitReadLock(); } } public void AddQuote() { _mutex.EnterWriteLock(); try { _quotes.Add(quote); } finally { _mutex.ExitWriteLock(); } } public void Dispose() { _mutex.Dispose(); } } </code></pre> <p>Or if you are using .Net 4 or above there are many wonderful concurrently modifiable collections in <a href="http://msdn.microsoft.com/en-us/library/dd287108.aspx" rel="nofollow">the System.Collections.Concurrent namespace</a> which you could probably use without any problem (they are lock free objects and are generally very quick - and <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/11/08/10235147.aspx" rel="nofollow">some performance enhancements are coming in .Net 4.5 too</a>!). </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