I am facing an issue in Arithmetic overflow, I have posted the detail in this question [Dictionary to ToList ArithmeticFlowException
however I have found the reason, when I call the method
Global.SereverConnections.TryGetValue(key, out connections);
it throws overflow exception, having count of connections is equal to -1.
public static IDictionary<string, ISet<ConnectionManager>> SereverConnections = new ConcurrentDictionary<string, ISet<ConnectionManager>>();
public static IList<ConnectionManager> GetUserConnections(string username)
{
//Key must not be null in any case return null if someone send and empty username
if (string.IsNullOrEmpty(username))
return null;
ISet<ConnectionManager> connections;
Global.SereverConnections.TryGetValue(username, out connections);
//this will make the copy of the
//return (connections != null ? connections.ToList() ?? Enumerable.Empty<ConnectionManager>().ToList() : null);
//exception occurs in below line, and connections.Count==-1
return (connections != null ? connections.ToList() : null);
}
Global.SereverConnectionsis aConcurrentDictionary, and thus is thread-safe. But you are addingHashSets to it - and they are not thread-safe.You can't call
HashSet.ToList()at the same time as someone is adding items to it.You will need to use locking around all accesses to the
HashSetto ensure that you don't have threading issues. Or switch to usingConcurrentDictionaryinstead ofHashSet(as per https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework).