首页 > 编程语言 > 详细

Delphi Event Bus进阶(一)控制订阅方法的线程模式

时间:2021-03-15 19:23:37      阅读:59      评论:0      收藏:0      [点我收藏+]

上文根据Delphi Event Bus开源项目自带的例子,对其基本用户法做了介绍,相信通过这个例子,你也能明白如果使用Delphi Event Bus到自己的项目中,让项目代码更解耦,易维护与易扩展。

今天,进一步说说如何更深入的使用Delphi Event Bus。

首先,想说的是对于订阅方法的注解,如何定义当他执行时,用什么样的线程。

当我们用[Subscribe]定义一个订阅方法时,这个方法是在主线程中执行,还是在单独的线程中执行?这一点对于我们来说,是必须要清晰的。看下面的代码:

    [Subscribe]
    procedure ReceiveFrameNotification(AEvent:IFrameNotifyMainEvent);

这里,我们要知道[Subscribe]还能用TThreadMode进一步注解,等明白了如何使用TThreadMode,才能正确回答上面的问题。接下来,看一下TThreadMode的定义:

  /// <summary>
  ///   Thead mode of the subscriber method.
  ///  订阅方法的线程模式
  /// </summary>
  TThreadMode = (
    /// <summary>
    ///   The subscriber method will be invoked in the same posting thread where
    ///   IEventBus.Post is called.
    /// 订阅方法将在IEventBus.Post时的线程中执行,如果在主线程中Post,那么订阅方法就在主线程中执行,如果在子线程中执行,那么订阅方法就在这个子线程中执行。
    /// </summary>
    Posting,

    /// <summary>
    ///   The subscriber method will be invoked in the main thread.
    ///订阅方法在主线程中执行
    /// </summary>
    Main,

    /// <summary>
    ///   The subscriber method will be invoked asynchronously in a new thread
    ///   other than the posting thread.
    ///订阅方法将在新的子线程中执行
    /// </summary>
    Async,

    /// <summary>
    ///   If the posting thread is the main thread, the subscriber method will
    ///   be invoked asynchronously in a new thread other than the posting
    ///   thread. If the posting thread is NOT the main thread, the subscriber
    ///   method will be invoked synchronously in the same posting thread.
    ///保证在子线程中执行,如果在主线程中Post,那么订阅方法将在一个新的子线程中执行,如果Post在子线程中调用,那么订阅方法将和Post所在的线程中执行。
    /// </summary>
    Background
  );

根据作者的源代码中注释做了翻译,默认情况下,[Subscribe]线程模式为TThread.Posting,也就是在post时所在的线程中执行。现在你可以回答上面的问题了。那如何定义[Subscribe]的线程模式呢?象下面这样,让ReceiveFrameNotification在主线程中执行:

    [Subscribe(TThreadMode.Main)]
    procedure ReceiveFrameNotification(AEvent:IFrameNotifyMainEvent);

出差路上,要下车了,现到这里。

 

Delphi Event Bus进阶(一)控制订阅方法的线程模式

原文:https://www.cnblogs.com/kinglandsoft/p/14539211.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!