Delphi: Pitfalls of Anonymous methods and Capture

I was writing a web request handler when I ran into a problem. I was plugging in multiple handlers, but only one of them actually worked.

Why?

To get to the essence of it, this doesn’t work

procedure TMyClass.Setup;
var
  Handler: THandlerClass;
  hType: THandlers;
begin
  Broker.Clear;
  for hType in [foo, bar]
  do begin
    case hType of
      foo: Handler := TFoo.Create;
      bar: Handler := TBar.Create;
    end;
    Broker.AddHandler(Handler.OnHandle);
  end;
end;

Zipped example source code: https://drive.google.com/open?id=1RxOxOlYOrjqPryW7vGNw40VTLav6IN_M

Continue reading “Delphi: Pitfalls of Anonymous methods and Capture”