Is the list order of a ConcurrentDictionary guaranteed?
Asked Answered
B

2

7

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?

Bagwell answered 16/11, 2013 at 15:21 Comment(3)
Sort by the a DateTime value when displaying the data.Ruiz
@Ruiz I was planning on doing that, but its sort of a workaround. Id like to understand why it happens first.Bagwell
Related: Is ConcurrentDictionary always add item by order in C#?Geomancer
T
10

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.

Trygve answered 16/11, 2013 at 15:25 Comment(0)
P
4

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

Palila answered 16/11, 2013 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.