{
private static QueueServicePool _instance = new QueueServicePool();
public static QueueServicePool Instacne
{
get
{
return _instance;
}
}
private QueueServicePool()
{
this.ServiceList = new List<QueueService>();
}
private List<QueueService> ServiceList;
public void Init(int threadNumbers)
{
for (int i = 0; i < threadNumbers; i++)
{
ServiceList.Add(new QueueService());
}
}
public void AddTask(QueueModel model)
{
List<int> taskNumberList = new List<int>();
foreach (QueueService serv in this.ServiceList)
{
taskNumberList.Add(serv.CurrentQueueCount);
}
ServiceList[taskNumberList.IndexOf(taskNumberList.Min())].AddToQueue(model);
}
}
public class QueueService
{
public QueueService()
{
this._signal = new ManualResetEvent(false);
this._queue = new Queue<QueueModel>();
_thread = new Thread(Process);
_thread.IsBackground = true;
_thread.Start();
}
public int CurrentQueueCount
{
get
{
return _queue.Count;
}
}
private bool _isFirst = true;
private Thread _thread;
// 用于通知是否有新任务需要处理的“信号器”
private ManualResetEvent _signal;
//存放任务的队列
private Queue<QueueModel> _queue;
private void Process()
{
while (true)
{
_signal.WaitOne();
_signal.Reset();
ExecuteTask();
}
}
private void ExecuteTask()
{
if (_queue.Count == 0)
{
_signal.Reset();
return;
}
QueueModel m = _queue.Dequeue();
Console.WriteLine("QueueCount:" + this.CurrentQueueCount + "\t" + "id:" + m.id + "," + "p1:" + m.p1 + "\n");
//Thread.Sleep(2000);
_signal.Set();
}
public void AddToQueue(QueueModel model)
{
_queue.Enqueue(model);
if (_isFirst)
_isFirst = false;
_signal.Set();
}
public void Wait()
{
this._signal.Reset();
}
public void Finished()
{
this._signal.Set();
}
}
public class QueueModel
{
public int id { get; set; }
public string p1 { get; set; }
/// <summary>
/// 动态设置属性
/// </summary>
/// <param name="attributeName"></param>
/// <returns></returns>
public object this[string propertyName]
{
get
{
PropertyInfo p = this.GetType().GetProperty(propertyName);
if (p == null)
return null;
return p.GetValue(this);
}
set
{
PropertyInfo p = this.GetType().GetProperty(propertyName);
if (p == null)
return;
p.SetValue(this, value);
}
}
}
调用:
class Program
{
static void Main(string[] args)
{
QueueServicePool.Instacne.Init(3);//初始化3条线程&队列
process p = new process();
Thread t1 = new Thread(new ThreadStart(p.run));
Thread t2 = new Thread(new ThreadStart(p.run));
Thread t3 = new Thread(new ThreadStart(p.run));
Thread t4 = new Thread(new ThreadStart(p.run));
Thread t5 = new Thread(new ThreadStart(p.run));
Thread t6 = new Thread(new ThreadStart(p.run));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
t5.Start();
t6.Start();
Console.ReadLine();
}
}
public class process
{
public void run()
{
for (int i = 0; i < 2; i++)
{
QueueModel m = new QueueModel();
Random ran = new Random();
m.id = ran.Next(0, 10001);
m.p1 = Guid.NewGuid().ToString("N");
QueueServicePool.Instacne.AddTask(m);
}
}
}