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(項) ;
它突然消失,字典中不包含任何值。
我認爲這可能與多線程有關,但老實說我不知道!