原文网址: http://www.cnblogs.com/csdev

Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是:Apache License v2

开源地址是:https://github.com/MarcFletcher/NetworkComms.Net

优先级队列

 /// <summary>
    /// Queue which contains features to add and remove items using a simple priority model.
    /// 优先级队列  包含一个简单的优先级类型
    /// </summary>
    /// <typeparam name="TValue">The type of this queue</typeparam>
    public class PriorityQueue<TValue>
    {
        /// <summary>
        /// Each internal queue in the array represents a priority level.
        /// We keep the priority associated with each item so that when eventually returned the
        /// priority can be easily included.
        /// 内部字典 以优先级作为索引项
        /// </summary>
        private Dictionary<QueueItemPriority,Queue<KeyValuePair<QueueItemPriority, TValue>>> internalQueues = null;

        /// <summary>
        /// The list of priorities used to handle incoming packets.
        /// 用于处理传入的数据包的优先级列表
        /// </summary>
        private QueueItemPriority[] QueueItemPriorityVals;

        /// <summary>
        /// The number of queues we store internally.
        /// 存储在内部的队列数量
        /// </summary>
        ;

        /// <summary>
        /// The total number of items currently in all queues
        /// 所有队列中的项目数
        /// </summary>
        ;

        /// <summary>
        /// Create a new instance of the priority queue.
        /// 创建一个新的优先级队列项实例
        /// </summary>
        public PriorityQueue()
        {
            var vals = Enum.GetValues(typeof(QueueItemPriority)) as int[];
            Array.Sort(vals);

            this.numDistinctPriorities = vals.Length;

            QueueItemPriorityVals = new QueueItemPriority[numDistinctPriorities];

            internalQueues = new Dictionary<QueueItemPriority,Queue<KeyValuePair<QueueItemPriority,TValue>>>(numDistinctPriorities);
            ; i < numDistinctPriorities; i++)
            {
                internalQueues[(QueueItemPriority)vals[i]] = new Queue<KeyValuePair<QueueItemPriority, TValue>>();
                QueueItemPriorityVals[i] = (QueueItemPriority)vals[i];
            }
        }

        /// <summary>
        /// Try adding an item to the priority queue.
        /// 添加项目到优先级队列项中
        /// </summary>
        /// <param name="item">Key is priority, lower number is lower priority, and value is TValue</param>
        /// <returns>True if an item was successfully added to the queue</returns>
        public bool TryAdd(KeyValuePair<QueueItemPriority, TValue> item)
        {
            lock (internalQueues)
            {
                internalQueues[item.Key].Enqueue(item);
                Interlocked.Increment(ref totalNumberQueuedItems);
            }

            return true;
        }

        /// <summary>
        /// Try removing an item from the priority queue
        /// 从优先级队列中删除相应的项目
        /// </summary>
        /// <param name="item">Key is priority, lower number is lower priority, and value is TValue</param>
        /// <returns>True if an item was successfully removed from the queue</returns>
        public bool TryTake(out KeyValuePair<QueueItemPriority, TValue> item)
        {
            // Loop through the queues in priority order. Higher priority first
            ; i >= ; i--)
            {
                // Lock the internal data so that the Dequeue
                // operation and the updating of m_count are atomic.
                lock (internalQueues)
                {
                    )
                    {
                        item = internalQueues[QueueItemPriorityVals[i]].Dequeue();
                        Interlocked.Decrement(ref totalNumberQueuedItems);
                        return true;
                    }
                    else
                        continue;
                }
            }

            // If we get here, we found nothing, return defaults
            item = , default(TValue));
            return false;
        }

        /// <summary>
        /// Try removing an item from the priority queue which has a priority of at least that provided.
        /// 从优先级队列中删除相应的项目   删除的项目至少具有参数指定的优先级
        /// </summary>
        /// <param name="minimumPriority">优先级  The minimum priority to consider</param>
        /// <param name="item">Key is priority, lower number is lower priority, and value is TValue</param>
        /// <returns>True if an item was successfully removed from the queue</returns>
        public bool TryTake(QueueItemPriority minimumPriority, out KeyValuePair<QueueItemPriority, TValue> item)
        {
            // Loop through the queues in priority order. Higher priority first
            ; i >= (int)minimumPriority; i--)
            {
                // Lock the internal data so that the Dequeue
                // operation and the updating of m_count are atomic.
                lock (internalQueues)
                {
                    )
                    {
                        item = internalQueues[QueueItemPriorityVals[i]].Dequeue();
                        Interlocked.Decrement(ref totalNumberQueuedItems);
                        return true;
                    }
                    else
                        continue;
                }
            }

            // If we get here, we found nothing, return defaults
            item = , default(TValue));
            return false;
        }

        /// <summary>
        /// The total number of items currently queued.
        /// 目前排队项目总数
        /// </summary>
        public int Count
        {
            get { return totalNumberQueuedItems; }
        }

        /// <summary>
        /// Copies queued items into the provided destination array. Highest priority items first descending until
        /// destination is full or there are no remaining items.
        /// 复制指定的优先级项目到数组中   从高优先级开始
        /// </summary>
        /// <param name="destination">The destination array</param>
        /// <param name="destStartingIndex">The position within destination to start copying to</param>
        public void CopyTo(KeyValuePair<QueueItemPriority, TValue>[] destination, int destStartingIndex)
        {
            if (destination == null) throw new ArgumentNullException("destination", "Provided KeyValuePair<QueueItemPriority, TValue>[] cannot be null.");
            ) throw new ArgumentOutOfRangeException("destStartingIndex", "Provided int must be positive.");

            int remaining = destination.Length;
            KeyValuePair<QueueItemPriority, TValue>[] temp = this.ToArray();
            for (int i = destStartingIndex; i < destination.Length && i < temp.Length; i++)
                destination[i] = temp[i];
        }

        /// <summary>
        /// 复制所有的优先级项目到数组中   从高优先级开始
        /// </summary>
        /// <returns></returns>
        public KeyValuePair<QueueItemPriority, TValue>[] ToArray()
        {
            KeyValuePair<QueueItemPriority, TValue>[] result;

            lock (internalQueues)
            {
                result = new KeyValuePair<QueueItemPriority, TValue>[this.Count];
                ;
                ; i >= ; i--)
                {
                    )
                    {
                        internalQueues[QueueItemPriorityVals[i]].CopyTo(result, index);
                        index += internalQueues[QueueItemPriorityVals[i]].Count;
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// Gets a value indicating whether access to the PriorityQueue is synchronized (thread safe). Always returns true.
        /// 获取一个值,指示是否使用PriorityQueue是同步(线程安全)。始终返回true。
        /// </summary>
        public bool IsSynchronized
        {
            get { return true; }
        }

        /// <summary>
        /// Gets an object that can be used to synchronize access to the PriorityQueue. Throws an exception as all access is explicitly thread safe.
        /// 获取可用于同步访问一个对象的PriorityQueue  所有的访问都是现成安全时抛出异常 因为调用SyncRoot是不需要的
        /// </summary>
        public object SyncRoot
        {
            get { throw new Exception("All access to PriorityQueue is thread safe so calling SyncRoot() is unnecessary."); }
        }

        /// <summary>
        /// Clear the content of all queues
        /// 清除队列的内容
        /// </summary>
        public void Clear()
        {
            lock (internalQueues)
            {
                ; i < numDistinctPriorities; i++)
                    internalQueues[QueueItemPriorityVals[i]].Clear();
            }
        }
    }

介绍开源的.net通信框架NetworkComms框架 源码分析(十二)PriorityQueue的更多相关文章

  1. MyBatis框架的使用及源码分析(十二) ParameterHandler

    在StatementHandler使用prepare()方法后,接下来就是使用ParameterHandler来设置参数,让我们看看它的定义: package org.apache.ibatis.ex ...

  2. DotNetty网络通信框架学习之源码分析

    DotNetty网络通信框架学习之源码分析 有关DotNetty框架,网上的详细资料不是很多,有不多的几个博友做了简单的介绍,也没有做深入的探究,我也根据源码中提供的demo做一下记录,方便后期查阅. ...

  3. 深入理解分布式调度框架TBSchedule及源码分析

    简介 由于最近工作比较忙,前前后后花了两个月的时间把TBSchedule的源码翻了个底朝天.关于TBSchedule的使用,网上也有很多参考资料,这里不做过多的阐述.本文着重介绍TBSchedule的 ...

  4. Spark RPC框架源码分析(二)RPC运行时序

    前情提要: Spark RPC框架源码分析(一)简述 一. Spark RPC概述 上一篇我们已经说明了Spark RPC框架的一个简单例子,Spark RPC相关的两个编程模型,Actor模型和Re ...

  5. 设计模式(十五)——命令模式(Spring框架的JdbcTemplate源码分析)

    1 智能生活项目需求 看一个具体的需求 1) 我们买了一套智能家电,有照明灯.风扇.冰箱.洗衣机,我们只要在手机上安装 app 就可以控制对这些家电工作. 2) 这些智能家电来自不同的厂家,我们不想针 ...

  6. 设计模式(二十一)——解释器模式(Spring 框架中SpelExpressionParser源码分析)

    1 四则运算问题 通过解释器模式来实现四则运算,如计算 a+b-c 的值,具体要求 1) 先输入表达式的形式,比如 a+b+c-d+e,  要求表达式的字母不能重复 2) 在分别输入 a ,b, c, ...

  7. $Django cbv源码分析 djangorestframework框架之APIView源码分析

    1 CBV的源码分析 #视图 class login (View): pass #路由 url(r'^books/$', views.login.as_view()) #阅读源码: #左侧工程栏--- ...

  8. ④NuPlayer播放框架之Renderer源码分析

    [时间:2016-11] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架,渲染器,render] 0 导读 之前我们分析了NuPlayer的实现代码,本文将重点聚 ...

  9. ⑤NuPlayer播放框架之GenericSource源码分析

    [时间:2017-01] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架,GenericSource] 0 导读 GenericSource是NuPlayer:: ...

  10. ③NuPlayer播放框架之类NuPlayer源码分析

    [时间:2016-10] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架] 0 引言 差不多一个月了,继续分析AOSP的播放框架的源码.这次我们需要深入分析的是N ...

随机推荐

  1. Android Activity的生命周期简单总结

    Android Activity的生命周期简单总结 这里的内容参考官方的文档,这篇文章的目的不是去总结Activity是如何启动,如何创造,以及暂停和销毁的,而是从实际开发中分析在Activity各个 ...

  2. MVVM架构~Knockoutjs系列之text,value,attr,visible,with的数据绑定

    返回目录 Knockoutjs是微软mvc4里一个新东西,用这在MVC环境里实现MVVM,小微这次没有大张旗鼓,而是愉愉的为我们开发者嵌入了一个实现MVVM的插件,这下面的几篇文章中,我和大家将一起去 ...

  3. MVVM架构~knockoutjs系列之验证信息自定义输出~再续

    返回目录 对于一个项目的表单验证,方式有很多,效果也有很多,具体使用哪种完成取决于产品这边,产品让你用什么,你就要用什么,而做为开发人员,我们要做的就是"整理近可能多的架构方式",这样才可以自由的应变 ...

  4. Gridview转发

    首页 开源项目 问答 动弹 博客 翻译 资讯 专题 城市圈 [ 登录 | 注册 ] 博客专区 > Reya滴水心的博客详情 Asp.net中GridView使用详解(很全,很经典) Reya滴水 ...

  5. jquery 之 Deferred 使用与实现

    观察者模式是开发中经常使用的模式,这个模式由两个主要部分组成:主题和观察者.通过观察者模式,实现主题和观察者的解耦. 主题负责发布内容,而观察者则接收主题发布的内容.通常情况下,观察者都是多个,所以, ...

  6. HTML基础笔记-02

    ---恢复内容开始--- 学习网站:W3School 一.HTML的认识 纯文本语言:只显示内容,不显示样式,也不能描述语义的文档,但是也不会乱码 语义:数据的含义就是语义,数据是符号,在这表示标签 ...

  7. 数据类型,隐式转换以及json,对象,引用类型,预解析 视频教程

    随便看看,需要有一点一点基础. 链接:http://pan.baidu.com/s/1c20pcOC 密码:xq2x

  8. word-wrap: break-word; break-word: break-all;区别

    word-break:break-all和word-wrap:break-word都是能使其容器如DIV的内容自动换行. 它们的区别就在于: 1,word-break:break-all 例如div宽 ...

  9. ObjectOutputStream和ObjectInputStream

    官方解释: ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream.可以使用 ObjectInputStream 读取(重构)对象.通过使用流中的文 ...

  10. 后端码农谈前端(CSS篇)第五课:CSS样式

    一.背景: CSS 允许应用纯色作为背景,也允许使用背景图像创建相当复杂的效果. 1.背景色 可以使用 background-color 属性为元素设置背景色.这个属性接受任何合法的颜色值. 例如: ...