If Delphi code was written with synchronize to serialize access to the main VCL thread, but this code then is used in a non-VCL application, will it synchronize with the mai
Is it dangerous to use synchronize in a non-VCL application?
Yes it is dangerous. If your main thread is not calling CheckSynchronize
then Synchronize
will result in deadlock.
Let's assume
- it is a non-VCL application which has a main thread which executes in an endless loop (or until terminated)
- the main thread does not call
CheckSynchronize
directly or in aWakeMainThread
handler- a secondary thread runs and executes
Synchronize(SomeMethod)
like in the example aboveWill the thread hang on the
Synchronize(SomeMethod)
line?
The call to Synchronize
will block the background thread until the main thread calls CheckSynchronize
. So, if the main thread never calls CheckSynchronize
, the background thread will block indefinitely.
The following program illustrates this:
program TheBigSleep;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes, Windows;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
procedure TMyThread.Execute;
begin
Synchronize(SysUtils.Beep);
end;
begin
with TMyThread.Create do
WaitForSingleObject(Handle, INFINITE);
//don't call WaitFor since that, in turn, calls CheckSynchronize
end.