I have been given the following code and tasked with making it thread safe:
public class HashtableWrapper
{
private Hashtable _cachedData;
public HashtableWrapper()
{
_cachedData = new Hashtable();
}
public void Add(object key, object value)
{
_cachedData[key] = value;
}
public object Get(object key)
{
return _cachedData[key];
}
}
I am not that well versed in threading but the following is some 'solutions' I have found/come up with:
Would it have something to do with making the Add and Get methods synchronised?
Making
_cachedData
static?Creating a synchronised wrapper around Hashtable: https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable.synchronized?view=netcore-3.1 (Unsure where to do this if this was the solution - after
_cachedData = new Hashtable();
maybe?)Using a lock object, like here: Making class fields thread-safe - for example:
private static object lockObject = new Object(); public void Add(object key, object value) { lock(lockObject) { _cachedData[key] = value; } }