Problem Using Synchronize

I need to execute a function in a separate thread and wait for the thread to finish.

For example, here is the original function:

Procedure Search; begin CallA; CallB; end; 

This is a modified function:

 Procedure Search; var testMyThread: TMyThread; Done: Boolean; begin // create a new thread to execute CallA testMyThread:=TMyThread.Create(False,Done); WaitForSingleObject(testMyThread.Handle, INFINITE ); if not Done then begin TerminateThread(testMyThread.Handle, 0); end else; CallB; end unit uMyThread; interface uses classes; type TMyThread = class(TThread) private { Private declarations } FDone: ^boolean; protected procedure Execute; override; public constructor Create(const aSuspended: boolean; var Done: boolean); procedure CallA; end; implementation uses uMain; constructor TMyThread.Create(const aSuspended: boolean; var Done: boolean); begin inherited Create(aSuspended); FDone := @Done; end; procedure TMyThread.CallA; begin // enumurating several things + updating the GUI end; procedure TMyThread.Execute; begin inherited; Synchronize(CallA); // << the problem FDone^ := true; end; end. 

Could you tell me why the thread code above does not work ( CallA never executes) if I use Synchronize inside TMyThread.Execute ?

+4
source share
2 answers

Since Synchronize will call the method in the application message loop. And using WaitForSingleObject, you simply remove all applications. Try the following:

  Procedure Search; var testMyThread: TMyThread; Done: Boolean; begin // create a new thread to execute CallA testMyThread:=TMyThread.Create(False,Done); while (not Done) and (not Application.Terminated) do Application.ProcessMessages; if not Application.Terminated then CallB; end 
+5
source

There is an event in the Delphi tthread class called onThreadTerminate. This is called in the context of the application thread when the thread leaves the execution method.

You can use this event in your application.

+1
source

All Articles