【问题标题】:contents of dictionary class vanishing, possible thread issue?字典类的内容消失,可能的线程问题?
【发布时间】:2013-03-12 08:19:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# multithreading visual-studio-2010 dictionary


    【解决方案1】:

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

    来自Dictionary documentation:

    一个字典可以同时支持多个阅读器, 只要集合没有被修改。即便如此,列举 通过集合本质上不是线程安全的过程。在 枚举与写访问竞争的罕见情况, 在整个枚举过程中必须锁定集合。为了让 集合被多个线程访问以进行读取和写入, 您必须实现自己的同步。

    有关线程安全的替代方案,请参阅 ConcurrentDictionary。

    这种类型的公共静态(在 Visual Basic 中为共享)成员是线程 安全。

    更多信息请参见this SO question and answer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多