I am trying to figure out concurrent collections in C#.
ConcurrentBag, ConcurrentDictionary and ConcurrentQueue.
Is it possible for multiple threads to add items to them EXACTLY at the same time? Or they wait one after the other?
I tried to examine their source code, but I really couldn’t tell for sure.
I see here that there is an answer for C++, but I would like to know if this is the case also for C#?
>Solution :
It’s not provable, at the software level. Meaning that you can’t write a program that can prove or disprove the theory that two items can be inserted by two threads in the same collection at exactly the same time.
One attempt to prove it would be to have a third thread acting as the observer, that would enumerate the collection in a tight loop while the other two threads are doing the two concurrent insertions. Let’s say that the observer thread observed zero elements in one enumeration and two elements in the next enumeration, what would this prove? A thread can be suspended by the operating system at any moment for a duration measured in milliseconds, so you haven’t learn anything conclusive about the issue at hand. The two insertion might have happened exactly the same time, or milliseconds apart from one another, who knows?
If you want to answer this question at the hardware level, then at this level the concept of "collection" does not exist. You have registers, CPU instructions, memory chips etc. There are no software objects to talk about at this level.