请原谅我,但我不太确定我的代码哪里出了问题!我正在创建一个多线程 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(entry);
它突然消失了,字典不包含任何值。
我认为这可能与多线程有关,但老实说我不知道!