I've coded an event queue system that supports subscribing/firing events with an arbitrary number of parameters of arbitrary types. So I basically declared a delegate that accepts arbitrary parameters using the params keyword. Then I declared a bunch of delegates that take up to 5 generic parameters to wrap up the actual delegate. So the subscriber can pass in functions of up to 5 parameters of any type.
Are there any significant performance concerns especially in a game since I wrapped the callback delegates 2 times? Memory usage might also be a problem (GC)?
public delegate void EventWrapper();
public delegate void EventWrapper<T>(T arg);
public delegate void EventWrapper<T1,T2>(T1 arg1, T2 arg2);
public delegate void EventWrapper<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
public delegate void EventWrapper<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate void EventWrapper<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
private static Dictionary<MethodInfo, EventQueue.EventHandler> listenerMapping;
private static EventQueue eventQueue;
public EventManager()
{
listenerMapping = new Dictionary<MethodInfo, EventQueue.EventHandler>();
eventQueue = new EventQueue();
}
public void Update()
{
eventQueue.Update();
}
#region System Events Subscribing
/// <summary>
/// Fire a System Event with any number of parameters in ragnge 1~5. Make sure to match the number of parameters between firers and subscribers
/// </summary>
public static void FireSystemEvent(SystemEvents e, params object[] param)
{
PrintError(eventQueue.FireSystemEvent(e,param));
}
/// <summary>
/// 0 Parameter event register. Make sure to match the number of parameters between firers and subscribers
/// </summary>
public static void SubscribeSysEvent(SystemEvents e, EventWrapper callback)
{
EventQueue.EventHandler wrapper = (object[] param) =>
{
if (!ValidateEventParams(param, 0, 0, e, GameEvents.None)) return;
callback?.Invoke();
};
PrintError(SubscribeSys(e, wrapper, callback.Method));
}
public static void UnsubscribeSysEvent(SystemEvents e, EventWrapper callback) { UnsubscribeSys(e, callback.Method); }
/// <summary>
/// 1 Parameter event subscribing. Make sure to match the number of parameters between firers and subscribers
/// </summary>
public static void SubscribeSysEvent<T>(SystemEvents e, EventWrapper<T> callback)
{
EventQueue.EventHandler wrapper = (object[] param) =>
{
if (!ValidateEventParams(param, 1, 1, e, GameEvents.None, typeof(T))) return;
callback?.Invoke((T)param[0]);
};
PrintError(SubscribeSys(e, wrapper, callback.Method));
}
public static void UnsubscribeSysEvent<T>(SystemEvents e, EventWrapper<T> callback) { UnsubscribeSys(e,callback.Method); }