年度变更建库软件5.0版本
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
3.4 KiB

6 months ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Kingo.ThreadManager
{
public class ThreadManager2
{
//public static ThreadManager2 Instance { get; } = new ThreadManager2();
private List<TaskInfo> TaskList = new List<TaskInfo>();
private List<CustomThread> ThreadList = new List<CustomThread>();
private int _ActiveCount;
//public int ActiveCount
//{
// get
// {
// return ThreadList.FindAll(f => f.IsActive).Count;
// }
//}
ManualResetEvent _PoolEvent = new ManualResetEvent(true);
private int _MaxThreadNum = -1;
public int MaxThreadNum
{
get
{
if (_MaxThreadNum == -1)
{
_MaxThreadNum = Environment.ProcessorCount - 2;
}
return _MaxThreadNum;
}
set
{
_MaxThreadNum = value;
}
}
public ThreadManager2()
{
}
public List<TaskInfo> GetTaskList()
{
return TaskList;
}
//private bool IsExt = false;
public void ExeTask()
{
while (true)
{
_PoolEvent.WaitOne();
TaskList.RemoveAll(p => p.IsComplete);
if (TaskList.Count == 0) break;
var t = TaskList.FirstOrDefault(f => f.IsWait);
if (t != null)
{
CustomThread taskExe = FindThread();
if (taskExe != null)
{
taskExe.Start(t);
}
else
{
_PoolEvent.Reset();
continue;
}
}
else
{
_PoolEvent.Reset();
}
}
}
public void AddTask(TaskInfo pTask)
{
lock (TaskList)
{
TaskList.Add(pTask);
_PoolEvent.Set();
}
//CustomThread t = FindThread();
//t.Start(pTask.ExeFun, pTask.Parameter, pTask.ExeComplatFun);
}
public CustomThread FindThread()
{
lock (ThreadList)
{
ThreadList.RemoveAll(p => p.IsActive);
//CustomThread task = ThreadList.FirstOrDefault(f => !f.IsActive);
//if (task == null)
//{
if (ThreadList.Count < MaxThreadNum * 3)
{
CustomThread task = new CustomThread(_PoolEvent);
ThreadList.Add(task);
return task;
}
else
{
return null;
}
//}
//else
//{
// return task;
//}
}
}
public void Test(object o)
{ }
public static void InitThreadList()
{
//Threads = new ArrayList();
//for (int i = 0; i < 1; i++)
//{
// CustomThread t = new CustomThread();
// Threads.Add(t);
//}
}
}
}