簡體   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