Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TThread's Synchronize Behavior

From what I understand, calling TThread's Synchronize will execute the synchronized code as if it was ran in the main thread. Let's say that in my main thread, I have one button:

procedure TForm3.Button1Click(Sender: TObject);
var
 A, B, C : String;
begin
 A := 'test1';
 B := 'test2';
 C := 'test3';
 Button1.Enabled := false;
end;

In a secondary thread, I have the following code:

procedure TestThread.ChangeButton1;
begin
 Form3.Button1.Enabled := true;
end;

(Don't pay attention to the code itself -- it's just an example and it's not supposed to mean anything.)

Say I click on Button1, and right after, while Button1Click is being executed, TestThread calls Synchronize(ChangeButton1); Can we know when ChangeButton1 is going to be run by the main thread? If so, is it going to be after the whole of Button1Click has been executed; or can it be among any of the four operations inside the procedure?

Sorry if it's a silly question. I have been unable to find the answer to that question. It would allow me to understand better how the Synchronize procedure works.

Thanks.

like image 787
Pascal Bergeron Avatar asked Dec 16 '22 01:12

Pascal Bergeron


1 Answers

A Synchronize() request is put into a queue and then a message is posted to the main message queue to signal that the Synchronize queue is pending. When the main message loop processes that message, the Synchronize() code is then executed. Button1Click() is also triggered by a window message, so the main message loop is blocked while Button1Click() is running. If Synchronize() is called during that time, the synched code will not execute until control is returned to the main message loop. So, to answer your question, ChangeButton1() will execute after Button1Click() has finished and exited.

like image 155
Remy Lebeau Avatar answered Dec 27 '22 02:12

Remy Lebeau