I have a list of EventHandlers: private List<EventHandler> eventHandlers;
I don't know what this list will contain or how big it will be, but I need to trigger another event once each event in this list has been raised at least once.
Is there a way to do this?
I have looked into subscribing to each event with a lambda expression or an anonymous function and passing a bool from another list that can be marked as True once the event has been raised, but I don't want to lose the ability to unsubscribe from this event later.
You could track the raised events in a HashSet<T>
. This has the advantage that elements are added only once to the set. Once the hash set has the same number of elements as the list of events, every event has been raised at least once.
private List<EventHandler> eventHandlers;
private readonly HashSet<EventHandler> raisedHandlers = new();
// Example of an event handler
private void Button1_Click(object sender, EventArgs e)
{
// TODO: do some work...
CheckCompleted(Button1_Click);
}
private void CheckCompleted(EventHandler handler)
{
raisedHandlers.Add(handler);
if (raisedHandlers.Count == eventHandlers.Count) {
CompletedEvent?.Invoke();
}
}