2017-08-21 25 views
0

我面對的算術溢出的問題,我已經發布了詳細的這個問題[Dictonary to ToList ArithmeticFlowExceptionDictonary返回對象-1 ArithemeticFlowException

但我已經找到了原因,當我調用該方法

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); 
    } 
+0

有沒有在你的代碼表明這是如何發生野生猜測:'Global.SereverConnections'從多個線程訪問,引起了字典,不一致的狀態結束了 –

+0

你可以在字典中當對象的數量等於-1時共享嗎? – bilal

+0

是的,我在多線程環境下使用它,我正在做負載測試@JeroenMostert – bilal

回答

1

Global.SereverConnectionsConcurrentDictionary,因此是thread-safe。但是你要添加HashSet s - 而且它們不是thread-safe

您不能在someone is adding items to it的同一時間致電HashSet.ToList()

您需要在對HashSet的所有訪問中使用鎖定,以確保您沒有線程問題。或改用ConcurrentDictionary代替HashSet(按https://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework).

+0

好的是他們的任何線程安全的哈希集? – bilal

+0

如果我將hashset替換爲ConcurrentBag,它會解決問題嗎? – bilal

+0

是有改變併發冠狀動脈的 – bilal