- edited description
Avoid duplicates in TEventBase.Add
Issue #387
resolved
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)
-
reporter -
repo owner - changed status to resolved
I will not extend the API for rare use cases - I would suggest you do the same as suggested for the exact same use case in .NET: https://stackoverflow.com/questions/399648/preventing-same-event-handler-assignment-multiple-times
- Log in to comment