Muhammad Irfan
Muhammad Irfan

Reputation: 31

Concurrent Collections and Linq

Is Concurrent Collections are thread safe when we use them in linq queries? and what is the difference between Concurrent Collection and Immutable Collections??

Upvotes: 2

Views: 799

Answers (2)

tytyryty
tytyryty

Reputation: 739

All linq methods work through IEnumerable so they use implementation of GetEnumerator method. From the source code of ConcurrentDictionary I can see the comment from Microsoft related to GetEnumerator implementation:

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after was called.

This means you can enumerate ConcurrentDictionary but it might be modified by other threads during enumeration so you can get partially updated dictionary as a result of enumeration. To prevent this you can take snapshot of dictionary by calling dict.ToArray before enumeration or by using dict.Keys or dict.Values - they take snapshot internally.

ConcurrentStack, ConcurrentQueue and ConcurrentBag work differently:

The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not reflect any updates to the collection after was called. The enumerator is safe to use concurrently with reads from and writes to the stack.

This means when you start iterating you get a snapshot of current stack/queue and so it can not be changed by other threads.

As for the difference between Concurrent and Immutable collections, Ariex answer gives you a good explanation.

Upvotes: 2

Ariex
Ariex

Reputation: 76

from what I understanding, immutable collections means you can only read its value but not change them, which will works fine in concurrent scenario since there is just all read. concurrent collection is like immutable collection, but provides you more function to allows you edit it. immutable collection is naturally thread safe, and concurrent collection is made to be thread safe

Upvotes: 1

Related Questions