user809409
user809409

Reputation: 511

Multi-threaded access to C# dictionary

I understand that C# dictionaries are not thread-safe when it comes to adding, reading and removing elements; however, can you access the Count Property of a C# dictionary in a thread safe way if another thread is writing, reading, and removing from the dictionary?

Upvotes: 3

Views: 3437

Answers (6)

Telastyn
Telastyn

Reputation: 528

It should be threadsafe in that it won't blow up, but I'm fairly sure it is not threadsafe in that it might not give you the correct count due to other threads manipulating the dictionary.

[Edit: as usr points out, just because it's currently threadsafe at this level does not mean that it will continue to be so. You have no guarantees]

Upvotes: 2

sll
sll

Reputation: 62484

Since property is a method call under the hood hood so really situation is not such simple as at first glance.

  • T1: Accessing Count property
  • T1: get_Count() call (some kind of JMP/GOTO ASM instruction)
  • T1: read variable which represents a number of items == 1
  • T2: addign a new item, real count becomes 2
  • T1: returns 1 but really there are already two items

So if an application logic relies on a Count property value - theoretically you could ends up with race condition.

Upvotes: 2

usr
usr

Reputation: 171178

First: This is dangerous thinking. Be very careful if you put such a thing into production. Probably, you should just use a lock or ConcurrentDictionary.

Are you comfortable with an approximate answer?

But: Reflector shows that count just reads some field and returns it. This is likely not to change forever. So you reasonably could take the risk in this case.

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51309

Rather than assuming, I went and looked at it in reflector:

public int Count
{
    get
    {
        // count and freeCount are local fields
        return (this.count - this.freeCount);
    }
}

So yes, it is "thread safe" in that accessing it will not cause corruption in the dictionary object. That said, I am not sure that I can think of any use case where getting the count with any accuracy is important if the dictionary is being accessed by another thread.

Upvotes: 0

Eddie Velasquez
Eddie Velasquez

Reputation: 573

Depending on what you want to achieve, you can protect the dictionary with a ReaderWriterLockSlim. This way you can have faster reads and only lock the dictionary when performing mutating operations.

Upvotes: 0

user610217
user610217

Reputation:

You could create the dictionary as a static readonly object, and lock it when modifying it... that should deal with most problems, I would think.

Upvotes: 0

Related Questions