同步将执行主线程中的代码。
一个很好的解释可以在这里找到Delphi TThread 类中的同步
您只需要阻止用户与您的应用程序的表单进行交互,例如。经过
procedure TTestThread.SynchThread;
begin
MessageBoxA (0, 'Hello', 'Test', MB_TASKMODAL);
end;
像您一样使用 MessageBoxA 不会阻止主线程对由用户与您的表单交互触发的事件做出反应,只需尝试
procedure TForm4.Button2Click(Sender: TObject);
begin
MessageBoxA (0, 'Hello', 'Test', 0);
// vs
// MessageBoxA (0, 'Hello', 'Test', MB_TASKMODAL);
end;
消息框A
同步将在主线程中执行可以显示(恕我直言)
type
TTestThread = class(TThread)
private
FSync:Boolean;
FCalled:TDateTime;
procedure SynchThread;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean;sync:Boolean);
end;
procedure TTestThread.SynchThread;
begin
MessageBox (0,PChar(DateTimeToStr(FCalled)+#13#10+DateTimeToStr(Now)),'Hello' , 0);
end;
procedure TTestThread.Execute;
begin
sleep(100); // give Caller Time to fell asleep
if Fsync then Synchronize (SynchThread) else SynchThread;
end;
constructor TTestThread.Create(CreateSuspended: Boolean;sync:Boolean);
begin
inherited Create(CreateSuspended);
FSync := Sync;
FCalled :=Now;
FreeOnTerminate := True;
end;
procedure StartThread(sync:Boolean);
var
TestThread : TTestThread;
begin
TestThread := TTestThread.Create (FALSE,sync);
end;
procedure TForm4.RunUnsynchronizedClick(Sender: TObject);
begin
StartThread(false);// no sync
Sleep(5000); // Stop messageloop
end;
procedure TForm4.RunSynchronizedClick(Sender: TObject);
begin
StartThread(true); // sync
Sleep(5000); // Stop messageloop
end;