microsoft / dotnet

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
https://devblogs.microsoft.com/dotnet/
MIT License
14.43k stars 2.21k forks source link

An item with the same key has already been added issue - .NET 8.0 #1452

Open stefano-venturini-zucchetti opened 4 weeks ago

stefano-venturini-zucchetti commented 4 weeks ago

I'm experiencing an unexpected behavior with a Dictionary<(int, int), int> that is intended to act as a cache. Despite implementing a locking mechanism to ensure thread safety, I encounter a duplicate key exception when attempting to add an entry to the dictionary.

Here is the relevant code snippet:

private readonly Dictionary<(int, int), int> _hashCodeCausalTypeCache = new Dictionary<(int, int), int>();
private readonly object _lockObj = new object();

.........................

lock (_lockObj)
{
    if (_hashCodeCausalTypeCache.TryGetValue(key, out var value))
    {
        causalType = value;
    }
    else
    {
        var dataTable = Globals.SelectDataTable(@$"SELECT ac.causal_type
                                               FROM trans_articles ta
                                               LEFT JOIN article_causals ac ON ac.id = ta.causal_id
                                               WHERE ta.transaction_id = {transactionId} AND ta.hash_code = {hashCode}");

        if (dataTable == null || dataTable.Rows == null || dataTable.Rows.Count == 0)
        {
            return;
        }

        causalType = SafeConvert.ToInt32(dataTable.Rows[0]["causal_type"]);

        _hashCodeCausalTypeCache.Add(key, causalType);
    }
}

Issue Details:

I would appreciate any insights into why this might be occurring and any potential solutions to resolve this issue. Thank you!