字典类的内容消失,可能存在线程问题



原谅我,但我不太确定我的代码哪里出错了!我正在创建一个多线程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(入口);

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

我认为这可能与多线程有关,但老实说我不知道!

字典不是线程安全的-请考虑使用ConcurrentDictionary。

来自Dictionary文档:

一个Dictionary可以同时支持多个reader,只要集合没有被修改。即便如此,列举通过集合本质上不是线程安全的过程。在枚举与写访问竞争的极少数情况下集合必须在整个枚举期间被锁定。允许由多个线程进行读写访问的集合;你必须实现你自己的同步。

有关线程安全的替代方法,请参见ConcurrentDictionary。

Public static(在Visual Basic中共享)这种类型的成员是thread安全。

最新更新