Home > Delphi > Delayed non-blocking callback function

Delayed non-blocking callback function

November 14, 2013 Leave a comment Go to comments

In my previous post regarding a delayed callback function under Delphi I should have pointed out that it was coded for a form-based environment. Meaning that it allows the GUI to remain responsive and other events to fire by calling application.processmessages at a regular intervals. It was indeed “blocking” in the sense that it also functions as a friendly alternative to the sleep API function.

For a complete non-blocking solution, one that truly “calls back later”, more or less a replica of the Smart Pascal callback (which essentially is the JavaScript callback), we have to add a bit more. Here is a minimalistic version of a OS friendly callback function:

  unit w3callback;

  interface

  uses System.SysUtils, Winapi.Windows, System.Generics.Collections;

  procedure w3_callback(const aCallback:TProc;ms:Integer);

  implementation

  var
  _LUT: TDictionary<UINT,TProc>;

  procedure w3_callback(const aCallback:TProc;ms:Integer);
    procedure w3_invoke(hwnd: HWND; uMsg: UINT;
              idEvent: UINT_PTR;dwTime: DWORD);stdcall;
    var
      mProc:  TProc;
    begin
      KillTimer(0,idEvent);
      if assigned(_LUT) then
      begin
        mproc:=_lut.Items[idEvent];
        _lut.Remove(idEvent);
        if assigned(mProc) then
        mproc;
      end;
    end;
  begin
    if Assigned(_LUT) then
    _LUT.add(SetTimer(0,0,ms,@w3_invoke),aCallback);
  end;

  initialization
  _LUT:=TDictionary<UINT,TProc>.Create;

  finalization
  if Assigned(_LUT) then
  FreeAndNil(_LUT);

  end.
Advertisements
  1. November 14, 2013 at 9:59 pm

    Much better (:

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: