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.