× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

C# Is Locking Required When Swapping Variable Reference in Multithreaded Application

Gayot Fow
Feb 05, 2015
<p>If you are using .NET 4 or+ you can use the new new thread safe collections...</p> <pre><code>BlockingCollection&lt;string&gt; list = new BlockingCollection&lt;string&gt;(); </code></pre> <p>The BlockingCollection class has thread-safe methods for adding and removing members, rather like the Producer Consumer design pattern.</p> <p>Threads can add and other threads can remove list members with no programming overhead.</p> <p>Additionally, it allows you to do things like this...</p> <pre><code> foreach (string i in list) { list.Take(); list.Add(i + 200); } </code></pre> <p>This code removes and adds to a collection while its enumerator is working, something that could never be done in c# prior to .NET 4. There is no additional need to declare it volatile.</p> <pre><code> foreach (string i in list) { new Task(() =&gt;list.Take()).Start(); new Task(() =&gt;list.Add(i + 200)).Start(); } </code></pre> <p>In this snippet, N*2 threads are started that all operate on the same list...</p> <p>The different behaviour implicit in using Concurrnt Collections may obviate the need for you to have two lists.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/8898529/C#%20Is%20Locking%20Required%20When%20Swapping%20Variable%20Reference%20in%20Multithreaded%20Application/8898837">Stack Overflow</a>.</p>
comments powered by Disqus