Reputation: 511
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
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
Reputation: 62484
Since property is a method call under the hood hood so really situation is not such simple as at first glance.
So if an application logic relies on a Count
property value - theoretically you could ends up with race condition.
Upvotes: 2
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
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
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
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