[fpc-pascal] Delphi compatible anonymous functions

Michael Schnell mschnell at lumino.de
Thu May 22 09:35:37 CEST 2014


On 05/21/2014 05:52 PM, Craig Peterson wrote:
> I think it's useful for encapsulating asynchronous callbacks and 
> improving readability by keeping the callback code near the setup 
> location and removing data marshalling scaffolding.

For complex asynchronous  events, I tested this:

  - Define a class (sibling of TObject) ) that holds some data and the 
procedure to be used in the asynchronous callback. The procedure has no 
parameters

  - To through the callback event, create an instance and fill the data 
structure in the instance and then use TThread.Queue to through the event:
    procedure TmyThread.Execute....
    begin
    ...
    AsyncEvent := TAsyncEvent.create;
    AsyncEvent.DataX := .....
    AsyncEvent.DataY := .....
Queue(AsyncEvent.DoIt);

  - now forget the variable AsyncEvent :-) .

  - some time later the main Thread calls DoIt
   here we go:
   procedure DoIt...
   begin
     X := DataX;
     Y := DataY;
     ... do stuff ...
     Free;
   end;

   Here, the procedure just frees it's own instance. This does not seem 
to be a problem. (Obviously exception handling needs to be added.)

So I get away without the use of Interfaces.

To me this seems like the most "pascalish" way to implement a "closure" 
for encapsulating asynchronous callbacks.

As syntax candy you might want to define a procedure as having a 
"closure" attribute and have same call free just before exiting (even 
when exiting by an exception).

-Michael



More information about the fpc-pascal mailing list