msg: tmsg;
begin
h[0] := fhandle;
if getcurrentthreadid = mainthreadid then
begin
waitresult := 0;
h[1] := syncevent;
repeat
{ this prevents a potential deadlock if the background thread
does a sendmessage to the foreground thread }
if waitresult = wait_object_0 + 2 then
peekmessage(msg, 0, 0, 0, pm_noremove);
waitresult := msgwaitformultipleobjects(2, h, false, 1000, qs_sendmessage);
checkthreaderror(waitresult <> wait_failed);
if waitresult = wait_object_0 + 1 then
checksynchronize;
until waitresult = wait_object_0;
end else waitforsingleobject(h[0], infinite);
checkthreaderror(getexitcodethread(h[0], result));
end;