繁体   English   中英

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

[英]Dictionary return object having count -1 ArithmeticFlowException

我在算术溢出中面临一个问题,我已在此问题中发布了详细信息[ ToList字典ArithmeticFlowException

但是当我调用该方法时,我已经找到了原因

Global.SereverConnections.TryGetValue(key, out connections);

它抛出溢出异常,连接数等于-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.SereverConnectionsConcurrentDictionary ,因此是线程安全的 但是您要向其添加HashSet ,并且它们不是线程安全的

您不能在有人向其中添加项目的同时调用HashSet.ToList()

您将需要对HashSet所有访问使用锁定,以确保没有线程问题。 或切换为使用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