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);
});
}
}
}
}