Search code examples
delphifiremonkey

How to queue some code to be executed at next cycle under firemonkey?


Under firemonkey, When i want to execute some code after the current "cycle", I do like this :

 TThread.createAnonymousThread(
   procedure
   begin
     TThread.queue(nil,
       procedure
       begin
         domycode
       end);
   end).start;

because if we are in the mainThread, then TThread.queue will execute the code immediatly. I m curious if their is not another way to do this than using a thread ?


Solution

  • In 10.2 Tokyo, a new TThread.ForceQueue() method was added to address RSP-15427 (Add an option to let TThread.Queue() run asynchronously when called by the main UI thread):

    TThread.ForceQueue(nil,
      procedure
      begin
        domycode
      end
    );
    

    No thread is needed.

    Prior to Tokyo, you would have to re-write the code if you don't want to use an anonymous thread to call TThread.Queue(). For instance, you could post yourself a delayed message with PostMessage() or PostThreadMessage(), and then do the work in the message handler. Or use the TApplication(Events).OnIdle event, like GolezTrol suggested.