Anonymous Methods, Methods and Procedures

High-level abstractions are very much based on anonymous methods. They are used all over the OtlParallel unit and they will also be used in your own code as they provide the simplest way to interact with the high-level threading. All of delegates (pieces of code that you 'plug in' into the high-level infrastructure) are declared as anonymous methods.

That, however, does not force you to write anonymous methods to use high-level multithreading. Thanks to the Delphi compiler, you can always provide a normal function/procedure or a method when an anonymous method is required.

For example, let's take a look at the IOmniWorkItemConfig interface. It announces (between other stuff) method OnExecute which accepts a delegate of type TOmniBackgroundWorkerDelegate.

TOmniBackgroundWorkerDelegate = reference to procedure (
  const workItem: IOmniWorkItem);
 
IOmniWorkItemConfig = interface
  function  OnExecute(const aTask: TOmniBackgroundWorkerDelegate):
    IOmniWorkItemConfig;
  ...
end; 

Let's assume a variable of the appropriate type, config: IOmniWorkItemConfig. You can then call the OnExecute method using an anonymous method.

config.OnExecute(
  procedure(const workItem: IOmniWorkItem)
  begin
    ...
  end);

Alternatively, you could declare a 'normal' procedure with the same signature (with the same parameters) and pass it to the OnExecute call.

procedure OnConfigExecute(const workItem: IOmniWorkItem)
begin
  ...
end;
 
config.OnExecute(OnConfigExecute);

The third option is to pass a method of some class to the OnExecute.

procedure TMyClass.OnConfigExecute(const workItem: IOmniWorkItem)
begin
  ...
end;
 
procedure TMyClass.DoConfig;
begin
  config.OnExecute(OnConfigExecute);
end;

These three options are valid whenever an anonymous method delegate can be used.

book/highlevel/intro/anonymousetal.txt · Last modified: 2012/11/14 11:50 by gabr
Recent changes RSS feed Debian Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki