Continuing my last thoughts on locking in C # and .NET,
Consider the following scenario:
I have a class that contains a specific collection (for this example, I used Dictionary<string, int> ), which is updated from the data source every few minutes using a specific method, which you can see below:
DataTable dataTable = dbClient.ExecuteDataSet(i_Query).GetFirstTable(); lock (r_MappingLock) { i_MapObj.Clear(); foreach (DataRow currRow in dataTable.Rows) { i_MapObj.Add(Convert.ToString(currRow[i_Column1]), Convert.ToInt32[i_Column2])); } }
r_MappingLock is an object designed to lock a critical section that updates the contents of a dictionary.
i_MapObj - dictionary object
i_Column1 and i_Column2 are the names of the data columns that contain the data to display.
Now I also have a class method that gets the string and returns the correct matched int based on the specified dictionary.
I want this method to wait for the update method to complete its execution, so at first glance, we could consider the following implementation:
lock (r_MappingLock) { int? retVal = null; if (i_MapObj.ContainsKey(i_Key)) { retVal = i_MapObj[i_Key]; } return retVal; }
This will prevent unexpected behavior and return value during dictionary update, but another problem arises: Since each thread that executes the above method tries to declare a lock, this means that if several threads try to execute this method at the same time, each of them will have to wait until the previous thread execution method and try to request a lock, and this is obviously undesirable behavior, since the above method is read-only purposes.
I was thinking of adding a logical element to the class that will be set to true or false if the dictionary is updated or not, and checks it in the read-only method, but there are other problems related to the racial state ...
Any ideas how to solve this gracefully?
Thanks again,
Miki