09.07.2011

Delphi and TTaskList

I was reading about some of the new features in Delphi XE in the new book from Marco Cantu, Delphi XE Handbook. (He also told me about them earlier this year in Frankfurt on the Delphi Developer Days, but I didn't found time to play around with it until now)
The newest Delphi comes with anonymous Threads, which are a very easy way to make your application multithreaded, which is very useful to make some big calculations in the background, while the UI is still responding. However, sometimes you need things to be done in order. Enter TTasklist:

type
  TProc = reference to procedure;
  TTaskList = class
  private
    fTasks : TThreadedQueue<TProc>;
    fTerminated : boolean;
    procedure start;
  public
    constructor Create;
    destructor Destroy; override;
    procedure addTask(aTask : TProc);
    procedure Terminate;
  end;

TTaskList uses a ThreadSafe Queue to store the tasks, which are basically anonymous methods. The constructor creates the queue and starts a new thread which executes one task after another.
constructor TTaskList.Create;
begin
  fTasks := TThreadedQueue<TProc>.Create;
  fTerminated := false;
  start;
end;

procedure TTaskList.addTask(aTask: TProc);
begin
  fTasks.PushItem(aTask);
end;

procedure TTaskList.start;
begin
  TThread.CreateAnonymousThread(
  procedure
  begin
    while not fTerminated do
    begin
      if fTasks.QueueSize > 0 then fTasks.PopItem.Invoke;
    end;
  end
  ).Start;
end;

procedure TTaskList.Terminate;
begin
  fTerminated := true;
end;

destructor TTaskList.Destroy;
begin
  Terminate;
  fTasks.Free;
  inherited;
end;

Download is available here.

Keine Kommentare: