0

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:

HollowDev
  • 63
  • 5
  • 3
    All you need is here (or in others online tutorials and printed books): [Threading in C#, by Joe Albahari](http://www.albahari.com/threading). And here: [Thread-Safe Collections](https://learn.microsoft.com/dotnet/standard/collections/thread-safe/) –  Jan 14 '21 at 18:51
  • 2
    If you are not well-versed in threading, don't make your own thread-safe collections or wrappers. If you MUST use a Hashtable, use the Synchronized wrapper, or, better yet, use a ConcurrentDictionary. – David L Jan 14 '21 at 18:53
  • Here is an example: [ConcurrentQueue.cs](https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentQueue.cs,3aca362f2b1eb019) –  Jan 14 '21 at 18:57
  • 1
    Does this answer your question? [Is Hashtable.Synchronized suitable for use as a simple cache in a multithreaded environment?](https://stackoverflow.com/questions/12554803/is-hashtable-synchronized-suitable-for-use-as-a-simple-cache-in-a-multithreaded) and [Minimal-locking thread-safe hashtable?](https://stackoverflow.com/questions/2111030/minimal-locking-thread-safe-hashtable) and [Thread-safe HashTable](https://stackoverflow.com/questions/15729614/thread-safe-hashtable) and [How to make a class Thread Safe](https://stackoverflow.com/questions/1344025/how-to-make-a-class-thread-safe) –  Jan 14 '21 at 19:01
  • 1
    @OlivierRogier Thanks, I'll take a look at all these – HollowDev Jan 14 '21 at 19:03

0 Answers0