我对 Delphi 中的线程处理很陌生。因此,我正在尝试制作一个简单的查询应用程序,该应用程序会对数据库进行一些调用并需要一些时间,因此我想提醒用户有一个后台进程,必须要有耐心。
我尝试了很多示例,但没有一个对我有用,请问有人可以向我展示一个可以工作的简单示例吗?
我知道我必须声明一种 TThread 类型,并使用 Create 和 Override Execute...等等,但从那时起我就迷失了...
使用 Delphi 7、SQL Server 2005 和 ADO、Windows XP sp3。-
谢谢。
最佳答案
是的,您声明了一个继承自 TThread 的新类型:
TMyWorkerThread = class(TThread)
end;
然后为 Execute() 添加函数重写:
TMyWorkerThread = class(TThread)
public
procedure Execute; override;
end;
当您启动线程时将调用该过程。它将与您的主程序并行执行。我们来写一下吧。
procedure TMyWorkerThread.Execute;
begin
//Here we do work
DoSomeWork();
DoMoreWork();
//When we exit the procedure, the thread ends.
//So we don't exit until we're done.
end;
如何使用这个?假设您想在用户单击按钮时开始工作。您编写一个 OnClick 处理程序:
procedure TMainForm.Button1Click(Sender: TObject);
begin
TMyWorkerThread.Create(false);
end;
就是这样。用户单击按钮后,您的线程将启动并继续执行您在执行中编写的任何操作。如果用户再次单击该按钮,则会启动另一个线程,然后再启动另一个线程 - 每次单击一个线程。它们都将并行运行,每个都执行 Execute() 中编写的所有操作,然后结束。
假设您想检查工作是否结束。为此,您必须将对线程的引用存储在某处:
TMainForm = class(TForm)
{...skipped...}
public
MyWorkerThread: TThread;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
//This time we make sure only one thread can be started.
//If one thread have been started already, we don't start another.
if MyWorkerThread<>nil then
raise Exception.Create('One thread have already been started!');
MyWorkerThread := TMyWorkerThread.Create(false);
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
//If the work is not over yet, we display message informing the user we're still working
if (MyWorkerThread<>nil) and (WaitForSingleObject(MyWorkerThread.Handle, 0)<>WAIT_OBJECT_0) then
MessageBox(Self.Handle, pchar("The work is not yet done!"), pchar("Still running"), MB_OK);
end;
如您所见,我们通过调用名为 WaitForSingleObject 的 Windows 函数来检查线程是否仍在运行。这个函数会等待,直到线程完成工作,或者超时,并且当我们指定超时为0时,如果线程还没有结束,它就会立即存在。
关于multithreading - 简单线程示例 Delphi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451138/