5

I am using a ConcurrentDictionary to store log-lines, and when I need to display them to the user I call ToList() to generate a list. But the weird thing is that some users receive the most recent lines first in the list, while they should logically be last.

Is this because ConcurrentDictionary doesnt guarantee a persistent order on the IEnumerate interface, or what can be the reason?

Sharun
  • 3,022
  • 6
  • 30
  • 59
Maestro
  • 9,046
  • 15
  • 83
  • 116
  • Sort by the a DateTime value when displaying the data. – usr Nov 16 '13 at 16:40
  • @usr I was planning on doing that, but its sort of a workaround. Id like to understand why it happens first. – Maestro Nov 16 '13 at 17:49
  • Related: [Is ConcurrentDictionary always add item by order in C#?](https://stackoverflow.com/questions/75226870/is-concurrentdictionary-always-add-item-by-thread-order-in-c) – Theodor Zoulias Feb 12 '23 at 02:07

2 Answers2

8

No ConcurrentDictionary (and Dictionary<T> for that matter) does not guarantee the ordering of the keys in the list. You'll have to use a different data type or perform the sorting yourself. For non-concurrent code you would use SortedDictionary<T>, but I don't believe there is an analogue in the concurrent collections.

shf301
  • 31,086
  • 2
  • 52
  • 86
4

No. The list order of ConcurrentDictionary is NOT guaranteed, lines can come out in any order.

driis
  • 161,458
  • 45
  • 265
  • 341