Dictionary is having duplicate keys
02:48 12 Jul 2024

Can a Dictionary have duplicate keys? Or is there something else, I am missing?

Here is the code

Dictionary initialization is at class level. StoredPoints.Keys Count = 4

[0]: "SNxxx_B"
[1]: "SNxxx60"
[2]: "SNxxx58"
[3]: "SNxxx_B"

We receive messages from Kafaka

await _kafkaService.ConsumeMessageWithWait(conf, _hostingServiceOption.Topics, source.Token, async (kafkaMessage) =>
{
    try
    {
        if (!ConnectionService.IsCalculationServiceConnected())
        {
            // cancel if no service in listening
            cts.Cancel();
            return;
        }
        NumberOfPointsReceived++;
        Stopwatch.Restart();
        var status = await _dataSenderService.SendMessage(kafkaMessage.Topic, kafkaMessage.Message.Key, kafkaMessage.Message.Value, kafkaMessage.Message.Timestamp);
        Stopwatch.Stop();
        TimeElapsedForProcessing += Stopwatch.ElapsedMilliseconds;
    }
    catch (Exception ex)
    {
        _logger.Fatal("{Exception}", ex);
    }
}, true, true);


public class DataSenderService
{
    public record KafkaMessage(string topic, string key, string message, Confluent.Kafka.Timestamp timestamp);
    public static Dictionary> StoredPoints = new Dictionary>();

    public async Task SendMessage(string topic, string key, string message, Confluent.Kafka.Timestamp timestamp)
    {
        if (!StoredPoints.ContainsKey(key))
         {
            StoredPoints.Add(key, new List());
         }
        StoredPoints[key].Add(kafkaMessage);
        return MessageStatus.Sent;
    }
}

I have compared the keys, both are same. Immediate window shows that and keys are also visible in screenshot

enter image description here

c# .net multithreading .net-8.0