简体   繁体   English

具有计数-1的字典返回对象ArithmeticFlowException

[英]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 我在算术溢出中面临一个问题,我已在此问题中发布了详细信息[ 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. 它抛出溢出异常,连接数等于-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 . Global.SereverConnectionsConcurrentDictionary ,因此是线程安全的 But you are adding HashSet s to it - and they are not thread-safe . 但是您要向其添加HashSet ,并且它们不是线程安全的

You can't call HashSet.ToList() at the same time as someone is adding items to it . 您不能在有人向其中添加项目的同时调用HashSet.ToList()

You will need to use locking around all accesses to the HashSet to ensure that you don't have threading issues. 您将需要对HashSet所有访问使用锁定,以确保没有线程问题。 Or switch to using ConcurrentDictionary instead of HashSet (as per https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework). 或切换为使用ConcurrentDictionary而不是HashSet (根据https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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