年度变更建库软件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.

80 lines
2.2 KiB

6 months ago
using System;
using System.Collections.Generic;
using System.Threading;
namespace Kingo.ThreadManager
{
public class ProcessManager
{
public static ProcessManager Instance { get; } = new ProcessManager();
private static readonly object lockObj = new object();
private List<CustomProcess> ProcessList = new List<CustomProcess>();
public string WorkerPath { get; set; }
private int _MaxThreadNum = -1;
public int MaxThreadNum
{
get
{
if (_MaxThreadNum == -1)
{
_MaxThreadNum = Environment.ProcessorCount - 2;
}
return _MaxThreadNum;
}
set
{
_MaxThreadNum = value;
}
}
private ProcessManager() { }
public void ExeTask(string pParm, ProcessHandler ProcessCallback = null)
{
var work = FindWorker();
if (work != null)
{
try
{
work.ExeTask(pParm, ProcessCallback);
}
catch (Exception ex)
{
}
}
else
{
}
}
public CustomProcess FindWorker()
{
lock (lockObj)
{
Thread.Sleep(1000);
//移除所有的退出的work
ProcessList.RemoveAll(p => p.IsExited);
foreach (var item in ProcessList)
{
if (item.IsExited)
{
continue;
}
if (!item.IsBusy)
{
return item;
}
}
//再移除一次
ProcessList.RemoveAll(p => p.IsExited);
if (ProcessList.Count < this.MaxThreadNum)
{
CustomProcess newWork = new CustomProcess(WorkerPath);
ProcessList.Add(newWork);
return newWork;
}
return null;
}
}
}
}