2013-03-12 23 views
0

原諒我,但我不太清楚在我的代碼中哪裏出了問題! 我正在創建一個多線程的tcp服務器,並試圖使用字典存儲字符串。代碼如下所示:字典類內容消失,可能的線程問題?

class Echo : Iprotocol 
{ 
    public Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
    private const int BUFFSIZE = 32; //buffer size 

    private Socket client_sock; //Socket 
    private Ilogger logger; // logger 

    public Echo(Socket sock, Ilogger log) 
    { 
     this.client_sock = sock; 
     this.logger = log; 
    } 
    public string handlewhois(string inname) 
    { 
     ArrayList entry = new ArrayList(); 
     string name = inname; 
     string message = null; 
     if (dictionary.ContainsKey(name) == true) 
     { 
      entry.Add(System.DateTime.Now + "Dictionary reference found at thread: " + Thread.CurrentThread.GetHashCode()); 
      message = dictionary[name]; 
     } 
     else 
     { 
      entry.Add(System.DateTime.Now + "Dictionary reference not found at thread: " + Thread.CurrentThread.GetHashCode()); 
      message = "ERROR: no entries found"; 
     } 
     logger.writeEntry(entry); 
     return message; 
    } 
    public string handlewhois(string inname, string inlocation) 
    { 
     ArrayList entry = new ArrayList(); 
     string name = inname; 
     string location = inlocation; 
     string message = null; 
     entry.Add(System.DateTime.Now + "Dictionary reference created or updated at thread: " + Thread.CurrentThread.GetHashCode()); 
     dictionary.Add(name, location); 
     message = "OK"; 
     logger.writeEntry(entry); 
     return message; 
    } 
} 

它運行完全正常,但是當我通過它在調試步驟,我看到的字典詞條創建的,但是當它到達線路: logger.writeEntry(項) ;

它突然消失,字典中不包含任何值。

我認爲這可能與多線程有關,但老實說我不知道​​!

回答

2

字典不是線程安全的 - 請考慮使用ConcurrentDictionary來代替。

Dictionary documentation

詞典可以支持多個讀者同時, 只要集合不會被改動。儘管如此,通過集合枚舉 本質上不是一個線程安全的過程。在枚舉與寫入訪問競爭的罕見情況下, 集合必須在整個枚舉期間被鎖定。爲了允許多個線程訪問 集合進行讀取和寫入,您必須實現自己的同步。

有關線程安全的替代方法,請參閱ConcurrentDictionary。

此類型的公共靜態(在Visual Basic中爲Shared)成員是線程 safe。

查看this SO question and answer瞭解更多信息。