"what's the best way of implementing a thread-safe dictionary?" Code Answer


as peter said, you can encapsulate all of the thread safety inside the class. you will need to be careful with any events you expose or add, making sure that they get invoked outside of any locks.

public class safedictionary<tkey, tvalue>: idictionary<tkey, tvalue>
    private readonly object syncroot = new object();
    private dictionary<tkey, tvalue> d = new dictionary<tkey, tvalue>();

    public void add(tkey key, tvalue value)
        lock (syncroot)
            d.add(key, value);

    public event eventhandler itemadded;

    protected virtual void onitemadded(eventargs e)
        eventhandler handler = itemadded;
        if (handler != null)
            handler(this, e);

    // more idictionary members...

edit: the msdn docs point out that enumerating is inherently not thread safe. that can be one reason for exposing a synchronization object outside your class. another way to approach that would be to provide some methods for performing an action on all members and lock around the enumerating of the members. the problem with this is that you don't know if the action passed to that function calls some member of your dictionary (that would result in a deadlock). exposing the synchronization object allows the consumer to make those decisions and doesn't hide the deadlock inside your class.

By Darrell Gadson on March 25 2022

Answers related to “what's the best way of implementing a thread-safe dictionary?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.