0

I have tested in a multithreaded scenario, seems the key-value pairs added by TryAdd() method is randomly ordered, even with adequate interval for the Adding action to complete. Sometime new item was added to the beginning, sometime at the end.

How can i make sure Tryadd() adds items in calling order?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Xiaoyuvax
  • 71
  • 6
  • 1
    Dictionaries and Sorting don't fit well. Dictionaries are hash based and at best sorted by that. It isn't a simple List internally where something get added to the end. If you need sorting i assume you have todo it explicitly yourself. – Ralf May 05 '22 at 10:09
  • And if that sorting relies on when it has been added to the dictionary i assume you have to add a timestamp to the data. – Ralf May 05 '22 at 10:10
  • It was told that ConcurrentDictionary is a good replacement for List under multihtreading scenario, now it seems it is not? – Xiaoyuvax May 05 '22 at 10:11
  • A dictionary is something else then a list. so they have different features. You don't need fast access by a key? Then don't use a dictionary. – Ralf May 05 '22 at 10:14
  • sadly I need both Order and Fast access. – Xiaoyuvax May 05 '22 at 10:15
  • But you were comparing to List. That also don't have fast key access. – Ralf May 05 '22 at 10:16
  • Orderby is a choice, but not quite ideal by performance. – Xiaoyuvax May 05 '22 at 10:16
  • I just mentioned that someone said if u want a List under multithreads, use but ConccurentDictionary. now i know it's not pefectly that way. – Xiaoyuvax May 05 '22 at 10:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244500/discussion-between-xiaoyuvax-and-ralf). – Xiaoyuvax May 05 '22 at 10:19
  • 1
    Related: [Is the list order of a ConcurrentDictionary guaranteed?](https://stackoverflow.com/questions/20020074/is-the-list-order-of-a-concurrentdictionary-guaranteed) – Theodor Zoulias May 05 '22 at 10:34
  • 1
    Re, "I need both Order and Fast access." Sometimes, you need more than one data structure. Is there a reason why you can't add the same items to both a dictionary _and_ a list? – Solomon Slow May 05 '22 at 14:43
  • Please provide enough code so others can better understand or reproduce the problem. – Community May 05 '22 at 19:30
  • @SolomonSlow it's a better solution than timestamp i feel. – Xiaoyuvax May 06 '22 at 02:52
  • @SolomonSlow But sadly i later finally found timestamp is better or maybe the only working solution in my case. lol but i will remember ur suggestion. – Xiaoyuvax May 06 '22 at 02:57

0 Answers0