How can this piece of code throw a KeyNotFoundException while the dictionary is readonly and never updated!? Most of the time it works fine

keynotfoundexception c#
system collections generic keynotfoundexception: the given key was not present in the dictionary
the given key was not present in the dictionary c# mysql
keynotfoundexception unity
c# exception message
try catch c#
dictionary trygetvalue
dictionary key exception

Edit: most of the time it works fine the error is exceptional.

On the line where this method is called the error report says it threw a KeyNotFoundException" im mapping an enum to a string (!im not updating the dictionary in any way its filled while getting declared!):

public Task<bool> UpdateStatusAsync(Some object, Status status)
{
    var somerequest = new Somerequest 
    {
        ...
        Status = MapDomainStatusToAclStatus(status.Type),
        ...
    };

    .............
}

Here is the mapping function:

private string MapDomainStatusToAclStatus(DomainStatus domainStatus)
{
    if (DictionaryDomainACLStatus.ContainsKey(domainStatus))
    {
        return DictionaryDomainACLStatus[domainStatus];
    }

    // Some refactor todo comment.
    switch (domainStatus)
    {
        case DomainStatus.Aborted:
            return "Some string";
    }

    Log.Info($"[MapDomainStatusToAclStatus] DomainStatus={domainStatus} cant be mapped to ACL status");
    return String.Empty;
}

Is that even possible?

Edit:

Since i got some replies about possible race condition I would like to add that the dictionary is declared like this:

 public static readonly Dictionary<DomainStatus, string> { values }

Edit2: My dictionary declaration:

public static readonly Dictionary<DomainStatus, string> DictionaryDomainACLStatus= new Dictionary<DomainStatus, string>
    {
            {DomainStatus.Approved, "TEXT" },
            {DomainStatus.Declined, "TEXT2" }
    };

No create update delete operations occur later on in the code.


Your static dictionary is shared across all threads and therefore not thread safe. Review if it really needs to be static or look at the ConcurrentDictionary which is thread safe.

How can this piece of code throw a KeyNotFoundException while the dictionary is readonly and never updated!? Most of the time it works fine · Ask Question. KeyNotFoundException. A KeyNotFoundException was thrown. This is likely caused by a lookup done on a key (one that is not present) in a Dictionary collection. As always we want a quick way to fix the problem. First, here we see some code that looks correct. But it has a severe flaw. This is the problem: you cannot look up a key that is not


Your problem is that you are within concurrent code, which means that multiple threads of code may run at the same time. So you have to make sure that concurrent operations are atomic, i.e. that that the operation is always executed as one step in a multi-threaded environment and another thread can not interrupt it.

The code...

if (DictionaryDomainACLStatus.ContainsKey(domainStatus))
{
    return DictionaryDomainACLStatus[domainStatus];
}

...is clearly not atomic, because it consists of two separate steps. Between ContainsKey and the indexer, another thread can modify the dictionary, which leads to your KeyNotFoundException if the modification is a Remove.

The first thought coming to mind would be to replace these two steps by...

if (DictionaryDomainACLStatus.TryGetValue(domainStatus, out string value)) {
    return value;
}

This will not help you though, since TryGetValue is in itself not atomic, which means it can be interrupted by another thread internally.

A common solution to this problem is to introduce a critical section with a lock:

lock (myCriticalSection) {
    if (DictionaryDomainACLStatus.ContainsKey(domainStatus))
    {
        return DictionaryDomainACLStatus[domainStatus];
    }
}

Any access of the dictionary has to be in the performed within a lock of the same critical section.

Another option would be to use a ConcurrentDictionary, which provides atomic operations. This will only work though if all accesses to the dictionary can be performed in one (atomic) step. That's why usually you will be better off with a lock.

Understand KeyNotFoundException and why it is encountered when using a Dictionary. Here we see some code that looks correct. But it has a severe flaw. Here: The KeyNotFoundException is thrown on the final line of the try-block. We can fix this exception by using the TryGetValue method on the Dictionary type​. Next up in our continued .NET Exception Handling series we come to the System.Collections.Generic.KeyNotFoundException. In most cases the System.Collections.Generic.KeyNotFoundException is thrown when attempting to access a Collection element using a key that doesn’t exist within said collection.


I found out the error lies in another piece of code and I overlooked it. Thank you all for thinking along with me. I will definately be more precise while debugging.

When you're ready to start coding, download our free guide to . NET exception gets thrown whenever we try to use a class reference Data bindings in WPF can be a huge time saver – when they work well. NET error, using too much exception handling with nested methods is definitely a mistake. KeyNotFoundException: The given key was not present in the dictionary its ♥♥♥♥♥♥♥ me off happens like every 10 minutes or less sometimes it can last like 2 hour before it happens but that is more of a miracle :


For example, the following piece of code is also an expression: up of a “plus” binary operator that works with a constant string expression When it comes to compiled expressions, one of the most common usage Throw( Expression. public class Benchmarks { private readonly Dictionary<string, int>  KeyNotFoundException: The given key was not present in the dictionary. We have a very weird issue going on with some code we are executing to query Coveo. We have the following code running in our test environment (thankfully it hasn't yet gone to production):


This will never throw a NullReferenceException , and doesn't need any extra utility classes. Empty) but that would no longer be a ?. operator, so would set is a bit more stable, I figured it was time to start updating the Noda Time 2.0 private static readonly Dictionary<TzdbStreamFieldId, Action<Builder,  "b.WeeklySalesBS.Add(gameWeekRecord, );" will create a New item in the dictionary with the Key gameWeekRecord. "b.WeeklySalesBS[gameWeekRecord] = "will look for an Existing item in the dictionary with the Key of gameWeekRecord and then assign it a new value. You don't have an item with key gameWeekRecord, you need to add it before you use it.


When I've got round to updating my continuous integration server, I'll merge onto private static readonly Dictionary<TzdbStreamFieldId, Action<Builder, We don't use the system default culture much in Noda Time, which the throw new KeyNotFoundException( "No calendar system for ID \{id} exists" );  We can see that, KeyNotFoundException was actually added to .NET Framework at a later time than ArgumentOutOfRangeException. In other words, it is possible that it was a deliberate decision to omit the storing of the key into the exception object.