Dictionary实现先进先出代替Queue

Queue删除其中一个元素比较麻烦,这是一个重码校验的类,主要处理是用Dictionary代替Queue了。目前使用下来还算稳定。代码贴出来给有缘人参考。

  /// <summary>
    /// 用Dictionary实现的重码校验队列
    /// 1、支持先进先出
    /// 2、支持移除队列里元素
    /// 3、支持从文件和数据库(外部数据源)里加载队列
    /// 4、支持把当前队列数据序列化成二进制文件
    /// </summary>
    public class RepeatCodeChecker : ConcurrentDictionary<long, string>
    {
        /// <summary>
        /// 工作计数
        /// </summary>
        public int WorkCount { get; set; }
        /// <summary>
        /// 最大元素个数
        /// </summary>
        public int MaxCount { get; set; }
        /// <summary>
        /// 加载已有数据到队列
        /// </summary>
        public Action<List<string>> LoadItemFromDataSource;
        /// <summary>
        /// 检查条码是否重复,并确定是否加入队列
        /// </summary>
        public Func<string, bool, bool> CheckIsRepeat;
        /// <summary>
        /// 将队列已有数据序列化成二进制文件 
        /// </summary>
        public Action<string> SaveToBinaryFile;
        /// <summary>
        /// 从二进制文件里加载队列
        /// </summary>
        public Func<string, bool> LoadQueueFormFile;
        /// <summary>
        /// 添加一个元素到队列末尾
        /// </summary>
        /// <param name="code"></param>
        public void Enqueue(string code)
        {
            var key = DateTime.Now.Ticks;
            if (ContainsKey(key))
            {
                key += (Count + 1);
            }
            TryAdd(key, code);
            WorkCount++;
            //如果达到最大元素个数移除最前面的元素
            if (MaxCount != 0 && Count > MaxCount)
            {
                Dequeue();
            }
        }
        /// <summary>
        /// 从队列移除第一个元素
        /// </summary>
        /// <returns></returns>
        public string Dequeue()
        {
            var minKey = this.Min(k => k.Key);
            string val;
            TryRemove(minKey, out val);
            return val;
        }
        /// <summary>
        /// 从队列里删除一个已经存在的元素
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool RemoveCode(string code)
        {
            try
            {
                var valObj = this.FirstOrDefault(t => t.Value == code);
                string val;
                TryRemove(valObj.Key, out val);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public RepeatCodeChecker()
        {
            //从外部数据源加载队列
            LoadItemFromDataSource = (list) =>
            {
                foreach (string code in list)
                    Enqueue(code);
            };
            //校验重码的委托声明
            CheckIsRepeat = (val, isAddtoQueue) =>
            {
                bool result = this.Any(item => item.Value == val);
                //不存在且需要加入则自动加入队列
                if (!result && isAddtoQueue)
                {
                    Enqueue(val);
                }
                return result;
            };
            //序列化成二进制文件
            SaveToBinaryFile = (filePath) =>
            {
                if (File.Exists(filePath))
                    File.Delete(filePath);
                using (FileStream fsWrite = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    try
                    {
                        bf.Serialize(fsWrite, this);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        fsWrite.Flush();
                        fsWrite.Close();
                    }
                }
            };
            //从文件加载队列
            LoadQueueFormFile = (filePath) =>
            {
                if (File.Exists(filePath))
                {
                    using (FileStream fs = new FileStream(filePath, FileMode.Open))
                    {
                        BinaryFormatter bf1 = new BinaryFormatter();
                        try
                        {
                            Dictionary<string, string> dict = bf1.Deserialize(fs) as Dictionary<string, string>;
                            if (dict != null)
                            {
                                foreach (var item in dict)
                                {
                                    Enqueue(item.Value);
                                }
                            }
                            return true;
                        }
                        catch
                        {
                            return false;
                        }
                        finally
                        {
                            fs.Close();
                        }
                    }
                }
                return false;
            };
        }
        /// <summary>
        /// 获取最前面的元素
        /// </summary>
        /// <returns></returns>
        public string FirstOrDefault()
        {
            if (Count == 0)
                return string.Empty;
            long minKey = this.Min(k => k.Key);
            return this[minKey];
        }
        /// <summary>
        /// 获取最前面的元素
        /// </summary>
        /// <returns></returns>
        public string LastOrDefault()
        {
            if (Count == 0)
                return string.Empty;
            long maxKey = this.Max(k => k.Key);
            return this[maxKey];
        }
    }

 

posted @ 2018-08-16 11:04  数据酷软件  阅读(634)  评论(0编辑  收藏