質問

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.

役に立ちましたか?

解決 2

Not a silly question.

Synchronize actually switches to the main thread temporarily, so it is not 'as if' - the code is literally run on the main thread. If the main thread is doing something when Synchronize is called, the Synchronize call must wait for the main thread to go idle. Similarly, if a synchronized call is executing, anything else that needs to take place on the main thread must wait for the synchronized call to complete.

So for this scenario there is no interrupting one operation mid-stream to switch to something else.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top