Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue procedure call on same [main] thread

Tags:

I am handling some specific TForm's event [CMControlListChanging], and need to modify that (inserted) control, but thing gets bad, when I try to do so, because apparently it's not meant to do this in the middle of VCL operation.

So I need to defer that control modification, by queuing the code away from the [CMControlListChanging] handler, to be called at later time.

Sure, I can do PostMessage stuff, but I want more general approach.

System.Classes unit contains

class procedure Synchronize(ASyncRec: PSynchronizeRecord; QueueEvent: Boolean = False); overload;

which could do the trick, but it checks, whether CurrentThread.ThreadID = MainThreadID and if yes, then call method I try to queue immediately.

Is the any good approach to deferred calls, at least on the main thread?

like image 920
AlekXL Avatar asked Aug 17 '16 13:08

AlekXL


1 Answers

Not sure if this is what you are looking for, but if you are on a recent Delphi version these Postpone methods may come in handy. They execute AProc in the main thread after applying an optional non-blocking delay.

uses
  System.Threading,
  System.Classes;

procedure Postpone(AProc: TThreadProcedure; ADelayMS: Cardinal = 0); overload;
begin
  TTask.Run(
    procedure
    begin
      if ADelayMS > 0 then begin
        TThread.Sleep(ADelayMS);
      end;
      TThread.Queue(nil, AProc);
    end);
end;

procedure Postpone(AProc: TThreadMethod; ADelayMS: Cardinal = 0); overload;
begin
  TTask.Run(
    procedure
    begin
      if ADelayMS > 0 then begin
        TThread.Sleep(ADelayMS);
      end;
      TThread.Queue(nil, AProc);
    end);
end;
like image 94
Uwe Raabe Avatar answered Sep 22 '22 16:09

Uwe Raabe