c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?

c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?,第1张

概述我在以下代码中使用.NET 4中的ConcurrentDictionary和ConcurrentQueue类. 这段代码是线程安全的吗?如果没有,我怎样才能使它成为线程安全的? public class Page{ public string Name {get; set; }}public class PageQueue{ private ConcurrentDicti 我在以下代码中使用.NET 4中的ConcurrentDictionary和ConcurrentQueue类.

这段代码是线程安全的吗?如果没有,我怎样才能使它成为线程安全的?

public class Page{    public string name {get; set; }}public class PageQueue{    private ConcurrentDictionary<int,ConcurrentQueue<Page>> pages =        new ConcurrentDictionary<int,ConcurrentQueue<Page>>();    public voID Add(int ID,Page page)    {        if (!this.pages.ContainsKey(ID))            this.pages[ID] = new ConcurrentQueue<Page>();        this.pages[ID].Enqueue(page);    }    public Page GetAndRemove(int ID)    {        Page lp = null;        if(this.pages.ContainsKey(ID))            this.pages[ID].TryDequeue(out lp);        return lp;    }}

演示:

public class Demo {     public voID RunAll()     {         for (int i = 0; i < 10; i++)             Task.Factory.StartNew(() => Run());     }     public voID Run()     {         PageQueue pq = new PageQueue();         pq.Add(1,new Page());         pq.GetAndRemove(1);     } }
解决方法 正如@Femaref正确指出的那样,代码中存在一些缺陷.我建议你利用 ConcurrentDictionary<K,V>提供的许多方法使代码线程安全而不需要锁定语句:
public class PageQueue{    private ConcurrentDictionary<int,ConcurrentQueue<Page>>();    public voID Enqueue(int ID,Page page)    {        var queue = this.pages.GetorAdd(ID,_ => new ConcurrentQueue<Page>());        queue.Enqueue(page);    }    public bool TryDequeue(int ID,out Page page)    {        ConcurrentQueue<Page> queue;        if (this.pages.TryGetValue(ID,out queue))        {            return queue.TryDequeue(out page);        }        page = null;        return false;    }}
总结

以上是内存溢出为你收集整理的c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?全部内容,希望文章能够帮你解决c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248360.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存