栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

实现线程安全字典的最佳方法是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现线程安全字典的最佳方法是什么?

如Peter所说,您可以将所有线程安全性封装在类中。您需要谨慎处理任何公开或添加的事件,以确保它们在任何锁之外都被调用。

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>{    private readonly object syncRoot = new object();    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();    public void Add(TKey key, TValue value)    {        lock (syncRoot)        { d.Add(key, value);        }        onItemAdded(EventArgs.Empty);    }    public event EventHandler ItemAdded;    protected virtual void onItemAdded(EventArgs e)    {        EventHandler handler = ItemAdded;        if (handler != null) handler(this, e);    }    // more IDictionary members...}

Edit: The MSDN docs point out that enumerating is inherently not thread
safe. That can be one reason for exposing a synchronization object outside
your class. Another way to approach that would be to provide some methods for
performing an action on all members and lock around the enumerating of the
members. The problem with this is that you don’t know if the action passed to
that function calls some member of your dictionary (that would result in a
deadlock). Exposing the synchronization object allows the consumer to make
those decisions and doesn’t hide the deadlock inside your class.




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465449.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号