Last post Feb 09, 2013 10:37 PM by dahla
Feb 09, 2013 10:12 AM|boeledi|LINK
Is a private collection in an instance of a class, threadsafe?
In order to illustrate my question, please have a look at the following "stupid" code.
As you will see "myClass" instantiates a "private" collection.
"anotherClass" instantiates "myClass" and populates the collection, then passes the instance of "myClass" to a shared method of another class "aThirdClass", which in turn "gets" and "sets" the contents of the collection.
So, the question, is this code ThreadSafe or do I systematically have to use the SyncLock, each time I need to get access to the contents of the hashTable?
Public Class myClass
Private _myCollection As HashTable = New HashTable(StringComparer.OrdinalIgnoreCase)
Public Sub AddValue(ByVal key As String, ByVal value As String)
If (Not _myCollection.ContainsKey(key)) Then
Public Function GetValue(ByVal key As String) As String
Dim strValue As String = String.Empty
If (_myCollection.ContainsKey(key)) Then
strValue = _myCollection(key)
Public Class anotherClass
Public Shared Sub myRoutine()
Dim anInstance As myClass = New myClass()
If (Not String.IsNullOrEmpty(anInstance.getValue("key3")) Then
Public Class aThirdClass
Public Shared Sub DoSomething(ByVal theInstance As myClass)
Dim strValue As String = theInstance.GetValue("key2")
Many thanks for your feedback
Feb 09, 2013 10:37 PM|dahla|LINK
Try reading this article http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx
Using a hashtable that is a threadsafe as you can get, like described in the article, without adding some kind of synchronization