using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AA
{
    public class AsynQueue<T>
    {
        //队列是否正在处理数据
        private int isProcessing;
        //有线程正在处理数据
        private const int Processing = 1;
        //没有线程处理数据
        private const int UnProcessing = 0;
        //队列是否可用
        private volatile bool enabled = true;
        private Task currentTask;
        public event Action<T> ProcessItemFunction;
        public event EventHandler<EventArgs<Exception>> ProcessException;
        private ConcurrentQueue<T> queue;

public AsynQueue()
        {
            queue = new ConcurrentQueue<T>();
            Start();
        }

public int Count
        {
            get
            {
                return queue.Count;
            }
        }

private void Start()
        {
            Thread process_Thread = new Thread(PorcessItem);
            process_Thread.IsBackground = true;
            process_Thread.Start();
        }

public void Enqueue(T items)
        {
            if (items == null)
            {
                throw new ArgumentException("items");
            }

queue.Enqueue(items);
            DataAdded();
        }

//数据添加完成后通知消费者线程处理
        private void DataAdded()
        {
            if (enabled)
            {
                if (!IsProcessingItem())
                {
                    currentTask = Task.Factory.StartNew(ProcessItemLoop);
                }
            }
        }

//判断是否队列有线程正在处理
        private bool IsProcessingItem()
        {
            return !(Interlocked.CompareExchange(ref isProcessing, Processing, UnProcessing) == 0);
        }

private void ProcessItemLoop()
        {

if (!enabled && queue.IsEmpty)
            {
                Interlocked.Exchange(ref isProcessing, 0);
                return;
            }
            T publishFrame;

if (queue.TryDequeue(out publishFrame))
            {

try
                {
                    ProcessItemFunction(publishFrame);
                }
                catch (Exception ex)
                {
                    OnProcessException(ex);
                }
            }

if (enabled && !queue.IsEmpty)
            {
                currentTask = Task.Factory.StartNew(ProcessItemLoop);
            }
            else
            {
                Interlocked.Exchange(ref isProcessing, UnProcessing);
            }
        }

/// <summary>
        ///定时处理线程调用函数 
        ///主要是监视入队的时候线程 没有来的及处理的情况
        /// </summary>
        private void PorcessItem(object state)
        {
            int sleepCount = 0;
            int sleepTime = 1000;
            while (enabled)
            {
                //如果队列为空则根据循环的次数确定睡眠的时间
                if (queue.IsEmpty)
                {
                    if (sleepCount == 0)
                    {
                        sleepTime = 1000;
                    }
                    else if (sleepCount <= 3)
                    {
                        sleepTime = 1000 * 3;
                    }
                    else
                    {
                        sleepTime = 1000 * 50;
                    }
                    sleepCount++;
                    Thread.Sleep(sleepTime);
                }
                else
                {
                    //判断是否队列有线程正在处理
                    if (enabled && Interlocked.CompareExchange(ref isProcessing, Processing, UnProcessing) == 0)
                    {
                        if (!queue.IsEmpty)
                        {
                            currentTask = Task.Factory.StartNew(ProcessItemLoop);
                        }
                        else
                        {
                            Interlocked.Exchange(ref isProcessing, 0);
                        }
                        sleepCount = 0;
                        sleepTime = 1000;
                    }
                }
            }
        }

public void Flsuh()
        {
            Stop();

if (currentTask != null)
            {
                currentTask.Wait();
            }

while (!queue.IsEmpty)
            {
                try
                {
                    T publishFrame;
                    if (queue.TryDequeue(out publishFrame))
                    {
                        ProcessItemFunction(publishFrame);
                    }
                }
                catch (Exception ex)
                {
                    OnProcessException(ex);
                }
            }
            currentTask = null;
        }

public void Stop()
        {
            this.enabled = false;
        }

private void OnProcessException(System.Exception ex)
        {
            var tempException = ProcessException;
            Interlocked.CompareExchange(ref ProcessException, null, null);

if (tempException != null)
            {
                ProcessException(ex, new EventArgs<Exception>(ex));
            }
        }

[Serializable]
        public class EventArgs<T> : System.EventArgs
        {

public T Argument;

public EventArgs() : this(default(T))
            {
            }

public EventArgs(T argument)
            {
                Argument = argument;
            }
        }
    }
}

c# 安全队列的更多相关文章

  1. 消息队列——RabbitMQ学习笔记

    消息队列--RabbitMQ学习笔记 1. 写在前面 昨天简单学习了一个消息队列项目--RabbitMQ,今天趁热打铁,将学到的东西记录下来. 学习的资料主要是官网给出的6个基本的消息发送/接收模型, ...

  2. 消息队列 Kafka 的基本知识及 .NET Core 客户端

    前言 最新项目中要用到消息队列来做消息的传输,之所以选着 Kafka 是因为要配合其他 java 项目中,所以就对 Kafka 了解了一下,也算是做个笔记吧. 本篇不谈论 Kafka 和其他的一些消息 ...

  3. Beanstalkd一个高性能分布式内存队列系统

    高性能离不开异步,异步离不开队列,内部是Producer-Consumer模型的原理. 设计中的核心概念: job:一个需要异步处理的任务,是beanstalkd中得基本单元,需要放在一个tube中: ...

  4. .net 分布式架构之业务消息队列

    开源QQ群: .net 开源基础服务  238543768 开源地址: http://git.oschina.net/chejiangyi/Dyd.BusinessMQ ## 业务消息队列 ##业务消 ...

  5. 【原创经验分享】WCF之消息队列

    最近都在鼓捣这个WCF,因为看到说WCF比WebService功能要强大许多,另外也看了一些公司的招聘信息,貌似一些中.高级的程序员招聘,都有提及到WCF这一块,所以,自己也关心关心一下,虽然目前工作 ...

  6. 缓存、队列(Memcached、redis、RabbitMQ)

    本章内容: Memcached 简介.安装.使用 Python 操作 Memcached 天生支持集群 redis 简介.安装.使用.实例 Python 操作 Redis String.Hash.Li ...

  7. Java消息队列--ActiveMq 实战

    1.下载安装ActiveMQ ActiveMQ官网下载地址:http://activemq.apache.org/download.html ActiveMQ 提供了Windows 和Linux.Un ...

  8. Java消息队列--JMS概述

    1.什么是JMS JMS即Java消息服务(Java Message Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送 ...

  9. 消息队列性能对比——ActiveMQ、RabbitMQ与ZeroMQ(译文)

    Dissecting Message Queues 概述: 我花了一些时间解剖各种库执行分布式消息.在这个分析中,我看了几个不同的方面,包括API特性,易于部署和维护,以及性能质量..消息队列已经被分 ...

  10. [数据结构]——链表(list)、队列(queue)和栈(stack)

    在前面几篇博文中曾经提到链表(list).队列(queue)和(stack),为了更加系统化,这里统一介绍着三种数据结构及相应实现. 1)链表 首先回想一下基本的数据类型,当需要存储多个相同类型的数据 ...

随机推荐

  1. BZOJ2002: [Hnoi2010]Bounce 弹飞绵羊(LCT)

    Description 某天,Lostmonkey发明了一种超级弹力装置,为了在 他的绵羊朋友面前显摆,他邀请小绵羊一起玩个游戏.游戏一开始,Lostmonkey在地上沿着一条直线摆上n个装置,每个装 ...

  2. Docker 搭建java+tomcat

    1. 准备java和tomcat的软件包 jdk-7u79-linux-x64.tar.gz apache-tomcat-7.0.57.tar.gz 2. 编辑Dockerfile 文件 vim Do ...

  3. unity3d 改动gui label颜色,定义颜色需除以256

    GUIStyle titleStyle2 = new GUIStyle(); titleStyle2.fontSize = 20; titleStyle2.normal.textColor = new ...

  4. android设置Activity背景色为透明的3种方

    方法一:这种方法比较简单,只有一个步骤,只需要在配置文件中把需要设置为透明的activity的样式设置为 Android:theme="@android:style/Theme.Transl ...

  5. 如何把excel同一个单元格内的文字和数字分别提取出来?

    平台:excel 2010 目的:把excel同一个单元格内的文字和数字分别提取出来 操作: 假设数据在A1单元格:如果文字在前,B1=left(A1,lenb(A1)-len(A1))可得文字,C1 ...

  6. VUE笔记 - 品牌后台 - v-for Splice Some Filter findIndex indexOf 直接return函数结果

    <body> <div id="app"> <div class="panel panel-primary"> <di ...

  7. COGS——C2274. [HEOI 2016] tree

    http://www.cogs.pro/cogs/problem/problem.php?pid=2274 ★☆   输入文件:heoi2016_tree.in   输出文件:heoi2016_tre ...

  8. winedt (latex 编译器)解决中文的问题(CJK & CTEX)

    主要是导入相关的库支持: 1. CJK \usepackage{CJK}:CJK,是中日韩的英文首字母的组合,处理中文需要先导入这个包: \begin{CJK*}{GBK}{song}:默认句式,表示 ...

  9. 微信支付v2开发(4) 交易通知

    本文介绍如何使用JS API支付时如何获得交易通知. 一.交易通知 用户在成功完成支付后,微信后台通知(POST)商户服务器(notify_url)支付结果.商户可以使用notify_url的通知结果 ...

  10. jmeter--十三种断言方式介绍

    jmeter中有个元件叫做断言(Assertion),它的作用和loadrunner中的检查点类似: 用于检查测试中得到的响应数据等是否符合预期,用以保证性能测试过程中的数据交互与预期一致. 使用断言 ...