简易实现threadPool

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace service
{
    public class ThreadPool
    {
        public List<Thread> threadContainer = null;
        public ConcurrentQueue<DataObjec> queueContainer = null;
        private  bool enabled = false;

        public  ThreadPool(int threadNum)
        {
            enabled = true;
            threadContainer = new List<Thread>(threadNum);
            queueContainer = new ConcurrentQueue<DataObjec>();
            //将thread加入列表
            for(var i=0;i<threadNum;i++)
            {
                Thread thread = new Thread(RunJob);
                threadContainer.Add(thread);
                thread.Start();
            }
        }

        private void RunJob()
        {
            DataObjec job = null;
            while (enabled && queueContainer != null)
            {
                queueContainer?.TryDequeue(out job);
                if (job == null)
                {
                    Thread.Sleep(2000);
                    continue;
                }
                try
                {
                    job?.Job.Invoke(job.Data);
                }
                catch (Exception e)
                {
                    job?.ErrorCallBack.Invoke(e);
                }
            }
        }

        public void AddTask(Action<object> job,object data,Action<Exception> e)
        {
            if(queueContainer!= null)
            {
                queueContainer.Enqueue(new DataObjec { Data = data, Job = job, ErrorCallBack = e });
            }
        }

        public void FinalExecution()
        {
            enabled = false;
            queueContainer = null;
            if(threadContainer!=null)
            {
                foreach(var t in threadContainer)
                {
                    t.Join();
                }
            }
            threadContainer = null;
        }
    }

    public class DataObjec
    {
        public object Data { get; set; }

        public Action<object> Job { get; set; }

        public Action<Exception> ErrorCallBack { get; set; }
    }

    public class Test
    {
        public static void Main()
        {
            ThreadPool threadPool = new ThreadPool(100);
            for (int i = 0; i < 500; i++)
            {
                threadPool.AddTask(obj =>
                {
                    Console.WriteLine($"{obj}--{Thread.CurrentThread.ManagedThreadId}");
                }, i, e =>
                {
                    Console.WriteLine(e.Message);
                });
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值