【问题标题】:AutoThread class in Delphi VCL?Delphi VCL中的AutoThread类?
【发布时间】:2013-09-28 17:10:00
【问题描述】:

Delphi VCL/RTL 有类似 AutoThread 类的东西吗?即,从例如派生的类的每个方法然后,TAutoThread 类将自动在单独的线程中执行,而无需编写任何线程特定的代码。

【问题讨论】:

    标签: multithreading delphi


    【解决方案1】:

    使用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; 
    

    【讨论】:

    • 在这样一个线程过程的内部,我可以使用“外部”的变量和对象吗?
    • 我刚刚从这样一个线程过程的内部使用“外部”的变量和对象进行了测试,它没有问题。
    • @user1580348,访问外部变量和对象是可能的,但请记住,这可能是不安全的,具体取决于您的实现。例如,在没有适当保护的情况下访问 VCL 是不行的。
    • 如何防止这种情况发生?可以在这个 Thread 过程中使用“Synchronize”吗?
    • 是的,TThread.Synchronize( nil, procedure begin UpdateComponent(...); end);,或者如果您想要异步更新,TThread.Queue(nil, procedure begin UpdateComponent(...); end);
    【解决方案2】:

    作为内置线程类的替代方案,您确实应该检查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);
    

    【讨论】:

    • Thx gabr ;-) 今年在 delphi 日也是一个关于你的框架的会议。
    猜你喜欢
    • 2015-02-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 2011-01-31
    • 2018-07-31
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多