1.队列类
public class MessageHandlerQueue : Queue<object> { //private Queue<object> messageQueue = new Queue<object>(); private Thread handleThread = null; private bool workFlag = true; //private static MessageHandler _instance; private object m_lock = new object(); private Action<Object> HandleFun = null; /// <summary> /// Initializes a new instance of the <see cref="MessageHandlerQueue"/> class. /// </summary> /// <param name="fun">消息处理函数</param> public MessageHandlerQueue(Action<Object> fun) { HandleFun = fun; } /// <summary> /// 线程执行函数,主要是调用 /// </summary> private void HandleMessage() { while (workFlag) { if (Count > 0) { try { var msg = new object(); lock (this.m_lock) { //LogHelper.GetLog("Server").Info("信息列表等待处理消息数:" + Count); Console.WriteLine("信息列表等待处理消息数:" + Count); msg = Dequeue(); } HandleFun(msg); } catch (Exception ex) { //LogHelper.GetLog("Server").Error(ExceptionHelper.GetExceptionDesc(ex)); Console.WriteLine(ex.ToString()); } } else { Thread.Sleep(100); } } } public void AppendMessage(object message) { lock (this.m_lock) { Enqueue(message); } } public void Start() { if (handleThread == null) { handleThread = new Thread(HandleMessage); } if (!handleThread.IsAlive) { handleThread.Start(); workFlag = true; } } public void Stop() { workFlag = false; } }
2.队列类使用
public MessageHandlerQueue _msgHdl; public MessageHandlerQueue MsgHandle { get { if (_msgHdl == null) { _msgHdl = new MessageHandlerQueue(ThreadFun); _msgHdl.Start(); return _msgHdl; } else return _msgHdl; } private set { _msgHdl = value; } }