C# 利用线程安全数据结构BlockingCollection实现多线程

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Danny.Infrastructure.Helper;

namespace Danny.Infrastructure.Collections
{
    /// <summary>
    /// 一个基于BlockingCollection实现的多线程的处理队列
    /// </summary>
    public class ProcessQueue<T>
    {
        private  BlockingCollection<T> _queue;
        private CancellationTokenSource _cancellationTokenSource;
        private CancellationToken _cancellToken;
        //内部线程池
        private List<Thread> _threadCollection;

        //队列是否正在处理数据
        private int _isProcessing;
        //有线程正在处理数据
        private const int Processing = 1;
        //没有线程处理数据
        private const int UnProcessing = 0;
        //队列是否可用
        private volatile bool _enabled = true;
        //内部处理线程数量
        private int _internalThreadCount;
     
        public event Action<T> ProcessItemEvent;
        //处理异常,需要三个参数,当前队列实例,异常,当时处理的数据
        public event Action<dynamic,Exception,T> ProcessExceptionEvent;

        public ProcessQueue()
        {
            _queue=new BlockingCollection<T>();
            _cancellationTokenSource = new CancellationTokenSource();
            _internalThreadCount = 1;
            _cancellToken = _cancellationTokenSource.Token;
            _threadCollection = new List<Thread>();
        }

        public ProcessQueue(int internalThreadCount):this()
        {
            this._internalThreadCount = internalThreadCount;
        }

        /// <summary>
        /// 队列内部元素的数量 
        /// </summary>
        public int GetInternalItemCount()
        {
            return _queue.Count;
        }

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

            _queue.Add(items);
            DataAdded();
        }

        public void Flush()
        {
            StopProcess();

            while (_queue.Count != 0)
            {
                T item=default(T);
                if (_queue.TryTake(out item))
                {
                    try
                    {
                        ProcessItemEvent(item);
                    }
                    catch (Exception ex)
                    {
                        OnProcessException(ex,item);
                    }
                }
            }
        }

        private void DataAdded()
        {
            if (_enabled)
            {
                if (!IsProcessingItem())
                {
                    ProcessRangeItem();
                    StartProcess();
                }
            }
        }

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

        private void ProcessRangeItem()
        {
            for (int i = 0; i < this._internalThreadCount; i++)
            {
                ProcessItem();
            }
        }

        private void ProcessItem()
        {
            Thread currentThread = new Thread((state) =>
            {
                T item=default(T);
                while (_enabled)
                {
                    try
                    {
                        try
                        {
                            item = _queue.Take(_cancellToken);
                            ProcessItemEvent(item);
                        }
                        catch (OperationCanceledException ex)
                        {
                            DebugHelper.DebugView(ex.ToString());
                        }

                    }
                    catch (Exception ex)
                    {
                        OnProcessException(ex,item);
                    }
                }

            });

            _threadCollection.Add(currentThread);
        }

        private void StartProcess()
        {
            foreach (var thread in _threadCollection)
            {
                thread.Start();
            }
        }

        private void StopProcess()
        {
            this._enabled = false;
            foreach (var thread in _threadCollection)
            {
                if (thread.IsAlive)
                {
                    thread.Join();
                }
            }
            _threadCollection.Clear();
        }

        private void OnProcessException(Exception ex,T item)
        {
            var tempException = ProcessExceptionEvent;
            Interlocked.CompareExchange(ref ProcessExceptionEvent, null, null);

            if (tempException != null)
            {
                ProcessExceptionEvent(this,ex,item);
            }
        }

    }
}

 

class Program
    {
        static void Main(string[] args)
        {
            ProcessQueue<int> processQueue = new ProcessQueue<int>();
            processQueue.ProcessExceptionEvent += ProcessQueue_ProcessExceptionEvent;
            processQueue.ProcessItemEvent += ProcessQueue_ProcessItemEvent;

            processQueue.Enqueue(1);
            processQueue.Enqueue(2);
            processQueue.Enqueue(3);

        }

        /// <summary>
        /// 该方法对入队的每个元素进行处理
        /// </summary>
        /// <param name="value"></param>
        private static void ProcessQueue_ProcessItemEvent(int value)
        {
            Console.WriteLine(value);
        }

        /// <summary>
        ///  处理异常
        /// </summary>
        /// <param name="obj">队列实例</param>
        /// <param name="ex">异常对象</param>
        /// <param name="value">出错的数据</param>
        private static void ProcessQueue_ProcessExceptionEvent(dynamic obj, Exception ex, int value)
        {
            Console.WriteLine(ex.ToString());
        }
    }

 

转自https://www.cnblogs.com/zw369/p/6675251.html

 

 

>对BlockingCollection使用的一点说明

var bc = new BlockingCollection<string>();

bc.Add("1");bc.Add("2");bc.Add("3");//添加

while (true)
{
	string value;
	if (bc.TryTake(out value))//取值方式1,尝试获取值,如果有值就会执行之后的操作
	{
		Console.WriteLine("Worker 1: " + value);
	}
}

while (true)
{
	Console.WriteLine("Worker 1: " + bc.Take());//取值方式2,直接取值,如果遇到没有值得情况,block
}

foreach (string value in bc.GetConsumingEnumerable())//取值方式3,遍历集合数据,有就取出来,没有阻塞自己,当有值添加进入,再次取值
{
	Console.WriteLine("Worker 1: " + value);
}




 

//用来结束任务
bc.CompleteAdding();//禁止向集合添加新的元素
bc.IsCompleted;//当CompleteAdding被执行,且集合中没有元素的时候为true


/*
    当我们使用CompleteAdding 之后 
    trytake take 在取的空集合值时会有异常产生,应配合IsCompleted使用
    GetConsumingEnumerable 元素在空集合时会自然结束,不会在阻塞自己
*/

 

>对封装的多线程队列解读

public ProcessQueue();//构造方法,默认创建1任务的多线程队列
public ProcessQueue(int internalThreadCount);//设定队列任务数
public int GetInternalItemCount();//获取集合资源数
public void Enqueue(T items);//向资源中添加对象,如果任务没有启动,初始化并启动
public void Flush();//结束任务,并将对可总的任务完成
private void DataAdded();//启动未开始的任务
private bool IsProcessingItem();//获取当前的任务启动状态,如果未启动,将其设为启动
private void ProcessRangeItem();//根据设定的任务数.开启生成对应任务
private void ProcessItem();//核心,开启一条线程安全的任务,并添加到任务集合
private void StartProcess();//将任务集合中的任务设置成执行状态
private void StopProcess();//停止任务
private void OnProcessException(Exception ex,T item);//对产生的异常进行处理

public event Action<T> ProcessItemEvent;//协议方法,生成多线程的执行代码,参数为从集合取出的数据
public event Action<dynamic,Exception,T> ProcessExceptionEvent;//协议方法,发生异常时的回调方法


//注:如果需要设定开启的任务数,一定要在  Enqueue(T items) 方法执行之前, 因为第一次执行该方法,会初始化任务,并且将任务状态设置成,执行中,此过程一次性,不可逆

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值