Skip to content

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

@tupini07

Description

@tupini07

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();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions