Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling RegisterLocal with the same callback more than once will result in the Dispatcher subscribing the callback multiple times #16

Open
tupini07 opened this issue Sep 18, 2020 · 0 comments
Labels
bug Something isn't working

Comments

@tupini07
Copy link
Contributor

Currently, in the EventDispatcher object we have a Dictionary<string, List<Subscription>> eventSubscriptions which associates the name of an event with a list of subscriptions (which in turn contain actions) that get called whenever this event happens. This means that if a RegisterLocal is invoked more than once for the same pair of event_name + action then whenever said event happens, the action will get executed multiple times (once for each time it appears in the list).

For example, this can happen in the case in which RegisterLocal is called in the constructor of an object, but said objects is instantiated multiple times. (As a note for anyone reading this: this shouldn't really happen since every object that subscribes it's methods to the eventManager via registerLocal should be a singleton. Otherwise, a memory leak may happen since a reference to the objects is owned by the EventDispatcher, and said objects would never get garbage collected).

A possible solution to this issue can be that of using a HashSet to hold the subscriptions of an event in the EventDispatcher instead of a List. We should look a bit more into this, but in principle, the HashSet shouldn't allow repeated entries of the Subscription entity.

An example of what I mean (dotnet fidddle can be seen here):

HashSet<Action> hs = new HashSet<Action>();

Action action1 = (() => {
    var s = 12;
    Console.WriteLine("Action 1");
});

Action action2 = (() => {
    var sss = 12;
    Console.WriteLine("Action 2");
});

// Add 'action1' twice
hs.Add(action1);
hs.Add(action1);

// Add 'action2' once
hs.Add(action2);

// should be 2
Console.WriteLine(hs.Count);

// should execute each action only once
foreach(var a in hs) {
    a();
}
@tupini07 tupini07 added the bug Something isn't working label Sep 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant