
Untitled
By: a guest on
Apr 25th, 2012 | syntax:
C# | size: 1.52 KB | hits: 16 | expires: Never
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hades.Utilities
{
public class BaseMessage
{
}
public class MessageDispatcher
{
protected class MessageHandler<T> where T : BaseMessage
{
public int ThreadID;
public string MessageName;
public Action<T> HandlerDelegate;
public Queue<T> Messages = new Queue<T>();
}
protected static System.Collections.Hashtable htHandlers = new System.Collections.Hashtable();
public static bool RegisterHandler<T>(int threadId, string msgName, Action<T> dele) where T : BaseMessage
{
if (htHandlers.ContainsKey(msgName))
return false;
htHandlers.Add(msgName, new MessageHandler<T>() { ThreadID = threadId, MessageName = msgName, HandlerDelegate = dele });
return true;
}
public static bool SendMessage<T>(string msgName, T msg) where T : BaseMessage
{
var info = htHandlers[msgName] as MessageHandler<T>;
if (info == null)
return false;
lock (info.Messages)
{
info.Messages.Enqueue(msg);
}
return true;
}
public static void Dispatch(int ThreadID)
{
foreach (MessageHandler<BaseMessage> info in htHandlers)
{
if (info.ThreadID != ThreadID)
continue;
Queue<BaseMessage> msgs = new Queue<BaseMessage>();
lock (info.Messages)
{
while (info.Messages.Count > 0)
msgs.Enqueue(info.Messages.Dequeue());
}
while (msgs.Count > 0)
info.HandlerDelegate(msgs.Dequeue());
}
}
}
}