using System;
namespace Sog.Service
{
///
/// 多工作线程,进行消息的任务分发处理,适用处理一个消息比较花费时间的操作,比如http操作处理,db操作处理
/// 对数据库来说,任务数量需要和表的数量相匹配,否则有可能会有问题,如果非要任务数量大于表的数量,请理清思路后
/// 仔细修改db相关代码
///
public class MessageTaskDistributor : Singleton
{
///
/// 所有任务对象的数组,在InitTask里初始化
///
private MessageTaskObj[] m_taskArray;
public void InitTask(uint taskNum, ServerApp app = null)
{
m_taskArray = new MessageTaskObj[taskNum];
for (int i = 0; i < m_taskArray.Length; i++)
{
m_taskArray[i] = new MessageTaskObj(i, app);
}
TaskCount = taskNum;
TraceLog.Debug("MessageTaskDistributor.InitTask taskNum {0}", taskNum);
}
///
/// 任务的数量,只读
///
public uint TaskCount { get; private set; }
///
/// 调用这个开始任务,每个任务的handler需要自己设置
///
public void StartAllTask()
{
TraceLog.Debug("MessageTaskDistributor.StartAllTask begin");
for (int i=0; i
/// 调用这个开始任务,每个任务的handler是同一个
///
/// 消息处理委托
public void StartAllTask(OnRequestPacketHandler handler)
{
TraceLog.Debug("MessageTaskDistributor.StartAllTask begin");
for (int i = 0; i < m_taskArray.Length; i++)
{
m_taskArray[i].Handler = handler;
m_taskArray[i].Start();
}
TraceLog.Debug("MessageTaskDistributor.StartAllTask success");
}
///
/// 关闭所有任务线程,注意每个任务关闭需要一些时间,因为要等待任务的消息处理完毕
///
public void CloseAllTask()
{
//允许重复调用
if(m_taskArray == null)
{
return;
}
TraceLog.Debug("MessageTaskDistributor.CloseAllTask begin");
for (int i = 0; i < m_taskArray.Length; i++)
{
m_taskArray[i].Close();
TraceLog.Debug("MessageTaskDistributor.CloseAllTask task {0} stop success", i);
}
m_taskArray = null;
TraceLog.Debug("MessageTaskDistributor.CloseAllTask all task stop success");
}
public MessageTaskObj GetTaskByIndex(int iTaskIndex)
{
if(m_taskArray == null)
{
TraceLog.Error("MessageTaskDistributor.GetTaskByIndex m_taskArray is null");
return null;
}
if(iTaskIndex >= m_taskArray.Length )
{
TraceLog.Error("MessageTaskDistributor.GetTaskByIndex invalid taskindex {0} , task count is {1}"
, iTaskIndex, m_taskArray.Length);
return null;
}
return m_taskArray[iTaskIndex];
}
///
/// 分发一个消息给任务
///
///
///
/// 任务下标,0开始
public void Distribute(uint remoteApp, StructPacket packet, int taskIndex)
{
MessageTaskObj task = GetTaskByIndex(taskIndex);
if(task == null)
{
TraceLog.Error("MessageTaskDistributor.Distribute can not find MessageTask by index {0}", taskIndex);
return;
}
TraceLog.Debug("MessageTaskDistributor.Distribute remote {0} MsgType {1} to task index {2}"
, ServerIDUtils.IDToString(remoteApp)
, packet.MsgID
, taskIndex);
task.AddRequestPacket(remoteApp, packet);
}
}
}