Concurrent dictionary thread safehttp://forums.asp.net/t/1798863.aspx/1?Concurrent+dictionary+thread+safeThu, 21 Mar 2013 00:15:28 -040017988634960015http://forums.asp.net/p/1798863/4960015.aspx/1?Concurrent+dictionary+thread+safeConcurrent dictionary thread safe <p>Im using MVC3. I have a question about ConcurrentDictionary.</p> <p>I have the following:</p> <p>public ConcurrentDictionary&lt;String, String&gt; myDictionary;</p> <p>There are two ways of adding data.</p> <p>myDictionary[&quot;SomeKey&quot;] = &quot;Some value&quot;</p> <p>and&nbsp;</p> <p>myDictionary.TryAdd(&quot;SomeKey&quot;, &quot;Some value&quot;);</p> <p></p> <p>Are both method threadsafe. I mean if two processes try to access the dictionary at the same time, it will not throw an exception?</p> <p></p> <p>Thanks</p> 2012-05-01T14:11:45-04:004960126http://forums.asp.net/p/1798863/4960126.aspx/1?Re+Concurrent+dictionary+thread+safeRe: Concurrent dictionary thread safe <p>only adding or fetching a reference from the dictionary is thread safe. you must make sure the item stored in the dictionary is thread and accessing the properties is thead safe. strings because they are imutable are thread safe for this use.</p> <p></p> 2012-05-01T15:08:42-04:004960365http://forums.asp.net/p/1798863/4960365.aspx/1?Re+Concurrent+dictionary+thread+safeRe: Concurrent dictionary thread safe thanks for your reply but I dont think that answers my question.I just gave an example by using string. I may using IList. anyway the question was which of the two methods I mentioned are thread safe? Thanks 2012-05-01T17:42:53-04:004966656http://forums.asp.net/p/1798863/4966656.aspx/1?Re+Concurrent+dictionary+thread+safeRe: Concurrent dictionary thread safe <p></p> <blockquote><span class="icon-blockquote"></span> <h4>pantonis</h4> Are both method threadsafe. I mean if two processes try to access the dictionary at the same time, it will not throw an exception?</blockquote> <p></p> <p>Yes they are thread safe. The ConcurrentDictionary class internally uses Monitor(C# lock). You can see <a href="http://weblogs.asp.net/imranbaloch/archive/2010/08/04/race-condition-in-asynccontroller.aspx"> this </a>for understanding why normal dictionaries are not thread safe.</p> 2012-05-05T07:28:54-04:005338756http://forums.asp.net/p/1798863/5338756.aspx/1?Re+Concurrent+dictionary+thread+safeRe: Concurrent dictionary thread safe <p><br> Please look at this <a href="http://spikesoftware.azurewebsites.net/?p=41">post</a> as this addresses how the contents are not threadsafe in regards to AddOrUpdate() and the concurrent dictionary. &nbsp;Yes the concurrentdictionary is threadsafe and in most situations you will not encounter an issue but be sure to read how threadsafe was defined.</p> 2013-03-21T00:15:28-04:00