简体   繁体   中英

Dictionary return object having count -1 ArithmeticFlowException

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.SereverConnections is a ConcurrentDictionary , and thus is thread-safe . But you are adding HashSet s 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 HashSet to ensure that you don't have threading issues. Or switch to using ConcurrentDictionary instead of HashSet (as per https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM