Avoid duplicates in TEventBase.Add

Issue #387 resolved
Olivier Sannier created an issue

Hello,

Would there be a way to avoid duplicates inside TEventBase.Add?
Maybe not directly, but via a new AddUnique method for instance?

I’m asking because I’m using TEvent<T> to be notified of various events and the registration into the event instance may be done multiple times from so many locations that it makes it difficult to check for duplicate calls to Add, except in Add itself.

Here is a suggested implementation, but I’m open to a better suited code:

procedure TEventBase.AddUnique(const handler: TMethodPointer);
var
  i: Integer;
begin
  if not Assigned(handler) then
    Exit;
  LockEnter;
  try
    for i := 0 to Count - 1 do
      if (TMethod(fHandlers[i]).Data = TMethod(handler).Data) and (TMethod(fHandlers[i]).Code = TMethod(handler).Code) then
        Exit;

    Add(handler);
  finally
    LockLeave;
  end;
end;

Comments (2)

  1. Log in to comment