131 lines
3.1 KiB
C#
131 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Threading;
|
|
|
|
namespace Thousandto.Code.Logic
|
|
{
|
|
/// <summary>
|
|
/// 生产者消费者模型线程池
|
|
/// </summary>
|
|
public class ChatThreadPool
|
|
{
|
|
//处理函数,处理数据
|
|
public delegate void HandleFunc(MSG_Chat.ChatResSC nodes);
|
|
//处理完成回调
|
|
public delegate MSG_Chat.ChatResSC FinishCallback();
|
|
|
|
//待处理的数据
|
|
private Queue<MSG_Chat.ChatResSC> _dataQueue;
|
|
//是否工作
|
|
private bool _working;
|
|
//线程个数
|
|
private int _threadNum = 1;
|
|
|
|
//处理函数
|
|
private HandleFunc _handleFunc;
|
|
//完成回调
|
|
private FinishCallback _finishCallback;
|
|
|
|
private List<Thread> _threadList;
|
|
|
|
//构造函数
|
|
public ChatThreadPool()
|
|
{
|
|
_working = true;
|
|
_dataQueue = new Queue<MSG_Chat.ChatResSC>();
|
|
_threadList = new List<Thread>();
|
|
|
|
//创建线程
|
|
for (int i = 0; i < _threadNum; ++i)
|
|
{
|
|
Thread workThread = new Thread(workFactory);
|
|
workThread.IsBackground = true;
|
|
workThread.Start();
|
|
|
|
|
|
_threadList.Add(workThread);
|
|
}
|
|
}
|
|
|
|
public void Destory()
|
|
{
|
|
_working = false;
|
|
_dataQueue.Clear();
|
|
_threadList.Clear();
|
|
}
|
|
|
|
public void SetHandleFunc(HandleFunc func)
|
|
{
|
|
_handleFunc = func;
|
|
}
|
|
|
|
public void SetFinishFunc(FinishCallback func)
|
|
{
|
|
_finishCallback = func;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 是否有线程存活
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public bool Running()
|
|
{
|
|
for (int i = 0; i < _threadList.Count; ++i)
|
|
{
|
|
if (_threadList[i].IsAlive)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 放入数据
|
|
/// </summary>
|
|
/// <param name="data"></param>
|
|
public void AddData(MSG_Chat.ChatResSC data)
|
|
{
|
|
_dataQueue.Enqueue(data);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 线程取数据
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private MSG_Chat.ChatResSC getData()
|
|
{
|
|
lock (_dataQueue)
|
|
{
|
|
if (_dataQueue != null && _dataQueue.Count > 0)
|
|
{
|
|
return _dataQueue.Dequeue();
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
|
|
|
|
private void workFactory()
|
|
{
|
|
while (_working)
|
|
{
|
|
Thread.Sleep(100);
|
|
|
|
MSG_Chat.ChatResSC data = getData();
|
|
|
|
if (_handleFunc != null)
|
|
{
|
|
_handleFunc(data);
|
|
}
|
|
if (_finishCallback != null)
|
|
{
|
|
_finishCallback();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|