你描述的不是使用线程的最佳方式。调用代码会被阻塞,直到线程完成。这完全抵消了并行运行代码的好处。你可以直接执行查询而不必使用线程:
procedure Requery;
var
...
begin
...
// run query
// do next jobs with query
...
end;
话虽如此,既然您正在使用XE6,您可以使用TThread.CreateAnonymousThread()
方法创建一个“本地”线程,指定一个匿名过程来“捕获”您想要它处理的变量,例如:
procedure Requery;
var
Event: TEvent;
H: THandle;
begin
Event := TEvent.Create;
try
TThread.CreateAnonymousThread(
procedure
begin
try
finally
Event.SetEvent;
end;
end
).Start;
H := Event.Handle;
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_ALLINPUT) = (WAIT_OBJECT_0+1) do
Application.ProcessMessages;
finally
Event.Free;
end;
...
end;
或者:
procedure Requery;
var
Thread: TThread;
H: THandle;
begin
Thread := TThread.CreateAnonymousThread(
procedure
begin
end
);
try
Thread.FreeOnTerminate := False;
H := Thread.Handle;
Thread.Start;
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_ALLINPUT) = (WAIT_OBJECT_0+1) do
Application.ProcessMessages;
finally
Thread.Free;
end;
...
end;
然而,当你让线程在后台运行而你做其他事情时,线程会更有用,并且当线程完成工作时再进行操作。例如:
procedure TMyForm.Requery;
var
Thread: TThread;
begin
Thread := TThread.CreateAnonymousThread(
procedure
begin
end
);
Thread.OnTerminate := QueryFinished;
Thread.Start;
end;
procedure TMyForm.QueryFinished(Sender: TObject);
begin
if TThread(Sender).FatalException <> nil then
begin
Exit;
end;
end;
TThread
只是一个用于构建线程的基本包装器 - 查看源代码即可。你缺少什么? - Sir Rufo