0

我在算术溢出中遇到问题,我已经在这个问题 [ Dictionary to 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); 
}
4

1 回答 1

1

Global.SereverConnections是 a ConcurrentDictionary,因此是线程安全的。但是您正在向HashSet其中添加 s - 它们不是thread-safe

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

您将需要对所有访问使用锁定,HashSet以确保您没有线程问题。或切换到使用ConcurrentDictionary而不是HashSet(根据https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework)。

于 2017-08-21T11:07:09.180 回答