Thursday, October 6, 2011

Creating chaining tasks

 In the unit BB.Task there is a class called TTask that helps creating task, it exposes this interface:

ITask = interface
    procedure AddParam(const aName, aValue: string);
    procedure AttachObject(aObject: TObject);
    function Available: boolean;
    procedure ClearParams;
    procedure ContinueWith(aTask: ITask); overload;
    function ContinueWith(aProc: TProc): ITask; overload;
    function ContinueWith(aEvent: TTaskEvent): ITask; overload;
    function GetAttachedTask: ITask;
    function GetAttachedObject: TObject;
    function GetEvent: TTaskEvent;
    function GetProc: TProc;
    function GetExceptionObject: TObject;
    function GetExceptionEvent: TExceptionEvent;
    function GetLock: ILock;
    function GetName: string;
    function GetParam(const aName: string): string;
    function GetTerminateEvent: TNotifyEvent;
    function GetAttachedObjectBehaviour: TAttachedObjectBehaviour;
    procedure Run;
    procedure Stop;
    procedure SendMessage(aTask: ITask; aMessage: TMessage); overload;
    procedure SendMessage(aTask: ITask; const aText: string); overload;
    procedure SetLock(aLock: ILock);
    procedure SetAttachedObjectBehaviour(aValue: TAttachedObjectBehaviour);
    procedure ReceiveMessage(aMessage: TMessage);
    procedure SetPriority(aValue: TThreadPriority);
    function Terminated: boolean;
    function Wait(aTime: cardinal): boolean;
  end;

Like this is really easy to create task based on plain methods, other tasks or closures, let's see an easy example:

unit Unit52;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BB.Task;

type
  TForm51 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    procedure One;
    procedure Two;
    procedure Three;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form51: TForm51;

implementation

{$R *.dfm}

procedure TForm51.FormCreate(Sender: TObject);
var
  TaskA, TaskB: ITask;

begin
  TaskB := TTask.Create(Three);

  TaskA := TTask.Create(One);
  TaskA.ContinueWith(Two).ContinueWith(
    procedure
    begin
      Beep;
    end
  ).ContinueWith(TaskB);
  TaskA.Run;
end;

procedure TForm51.One;
begin
  Sleep(1000);
end;

procedure TForm51.Three;
begin
  Sleep(3000);
end;

procedure TForm51.Two;
begin
  Sleep(2000);
end;

end.

  We are creating task A that will execute method one, after that, method ONE will execute method TWO and after that this task will launch the closure, at the end the closure will call the Task B that is executing method THREE. Is also possible to send messages and objects among different task.

Quite handy.

No comments:

Post a Comment