user11910061
user11910061

Reputation:

Should I Be Locking a Dictionary If I'm Only Reading From It?

I have a class that stores a dictionary. A thread may edit this dictionary in another function. Given that it is writing to this dictionary, I make sure that it is wrapped in a lock. For instance:

        public void SetModuleLogLevel(string module, LogLevel logLevel)
        {
            if (module == "Other" || !this._moduleToLogLevel.ContainsKey(module)) 
                return;

            lock (this._lock)
            {
                this._moduleToLogLevel[module] = logLevel;
            }
        }

I ahve another function that returns the value from this dictionary. For example,

        private bool IsUrgentToLog(string module, LogLevel logLevel)
        {
            if (!this._moduleToLogLevel.ContainsKey(module)) return false;

            lock (this._lock)
            {
                if (this._moduleToLogLevel[module] < logLevel) return true;
            }

            return false;
        }

Given that I'm only reading from this dictionary in this function, does it need a lock?

Upvotes: 3

Views: 44

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

Dictionary<TKey, TValue> makes no guarantees of anything when any thread is mutating it, i.e. you can have "any number of readers" or "at most one writer, and zero readers". So: if it can be mutated: yes, you do need a lock on the reads, to protect the other readers.

You may find it easier to use ConcurrentDictionary<TKey, TValue> (any number of readers and/or writers), or if you don't mind losing generics: Hashtable (at most one writer concurrent with any number of readers, i.e. you only need to synchronize writes).

Upvotes: 4

Related Questions