C#. Saving information about events and event handlers and removing handlers using this information
- by Philipp
I have an object which is creating several event handlers using lambda expressions, and I need to remove all handlers created in that object in one time.
I'm trying to create some unified static object which will 'know' which handler relates to which object and event if event handler was created through this static object.
I tried something like code below, but I don't understand how to save events and event handlers objects, to be able remove handlers in one time.
class Program {
static void Main(string[] args) {
var EventSender = new EventSender();
var EventReceiver = new EventReceiver(EventSender);
EventSender.Invoke(" some var ");
LinkSaver.RemoveEvent(EventReceiver); // ??
Console.ReadKey();
}
}
public class ObjLink{
public object Event;
public object Action;
}
public static class LinkSaver {
public static void SetEvent<T>(object obj, Action<T> Event, T Action) {
Event(Action);
var objLink = new ObjLink{Event = Event, Action = Action};
if (!Links.ContainsKey(obj)) Links.Add(obj, new List<ObjLink>{objLink});
else Links[obj].Add(objLink);
}
static Dictionary<object,List<ObjLink>> Links = new Dictionary<object, List<ObjLink>>();
public static void RemoveEvent(object obj){
foreach(var objLink in Links[obj]){
// objLink.Event -= objLink.Action; ???
}
}
}
public class EventReceiver {
public EventReceiver(EventSender obj) {
LinkSaver.SetEvent<EventSender.TestDelegate>(this, obj.SetEvent, str => Console.WriteLine(str + " test event!"));
}
}
public class EventSender {
public void Invoke(string var) {
if (eventTest != null) eventTest(var);
}
public void SetEvent(TestDelegate Action) {
eventTest += Action;
}
public delegate void TestDelegate(string var);
private event TestDelegate eventTest;
// by the way
public void RemoveFromEvent() {
foreach (var handler in eventTest.GetInvocationList())
eventTest -= (TestDelegate)handler;
}
}