【发布时间】:2013-09-28 17:10:00
【问题描述】:
Delphi VCL/RTL 有类似 AutoThread 类的东西吗?即,从例如派生的类的每个方法然后,TAutoThread 类将自动在单独的线程中执行,而无需编写任何线程特定的代码。
【问题讨论】:
标签: multithreading delphi
Delphi VCL/RTL 有类似 AutoThread 类的东西吗?即,从例如派生的类的每个方法然后,TAutoThread 类将自动在单独的线程中执行,而无需编写任何线程特定的代码。
【问题讨论】:
标签: multithreading delphi
使用Anonymous thread 可以制作类似于 AutoThread 类的东西。
只需传递一个匿名过程并调用线程。
var
aThread : TThread;
...
aThread :=
TThread.CreateAnonymousThread(
procedure
begin
// your code to execute in a separate thread here.
end
);
aThread.Start; // start thread and it will execute and self terminate
注意,这与从另一个类派生的类无关,但结果是相似的。您不必编写任何线程特定的代码。当然,您必须遵循正常的线程规则。
如果您需要在线程完成时收到通知,请在启动线程之前定义一个OnTerminate 方法。它将在主线程中执行。
aThread.OnTerminate := Self.ThreadFinishedNotification;
【讨论】:
TThread.Synchronize( nil, procedure begin UpdateComponent(...); end);,或者如果您想要异步更新,TThread.Queue(nil, procedure begin UpdateComponent(...); end);。
作为内置线程类的替代方案,您确实应该检查omnithreadlibrary。
这样效率更高,因为内置了调度程序、异步等待方法和线程同步。 还可以使用一些高级函数,例如 foreach.parallel(从 .net 知道)。
使用 OmniThreadLibrary,您可以简单地在线程中执行代码。
Async(
procedure begin
// threaded code
end).Await(
procedure begin
// main thread code, will be executed after threaded code finishes
end);
【讨论】: