【问题标题】:Store arbitrary data into object instance将任意数据存储到对象实例中
【发布时间】:2014-11-21 10:00:35
【问题描述】:

考虑以下示例:

type

  TTestClass = class
    public
      procedure method1; virtual;
  end;

  TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
  public
    vmi: TVirtualMethodInterceptor;
    ttc: TTestClass;
  end;

{ Initially SomeFlag is PostponeExecution }
procedure TForm2.FormCreate(Sender: TObject);
begin

  vmi := TVirtualMethodInterceptor.Create(TTestClass);
  ttc := TTestClass.Create;

  vmi.OnBefore :=
    procedure(Instance: TObject; Method: TRttiMethod;
      const Args: TArray<TValue>; out DoInvoke: Boolean;
        out Result: TValue)
    begin
      if { SomeFlag = DirectExecution } then
        DoInvoke := true
      else
      begin
        { SomeFlag := DirectExecution }
        TThread.CreateAnonymousThread(
          procedure
          begin                
            // Invoke() will trigger vmi.OnBefore 
            // because Instance is the proxified object
            // I want to keep "Self" to be the proxified object
            Method.Invoke(Instance, Args);
          end
        ).Start;
      end
    end;

  vmi.Proxify(ttc);

  ttc.method1;

end;

{ TTestClass }

procedure TTestClass.method1;
begin
  //  Do something async
end;

procedure TForm2.FormDestroy(Sender: TObject);
begin
  vmi.Unproxify(ttc);
  vmi.Free;
  ttc.Free;
end;

我希望挂钩的虚拟方法在线程中执行自身,即延迟/延迟其执行。

为此,我使用 TVirtualMethodInterceptor 来拦截给定类的虚拟方法。当调用虚拟方法时,会触发 vmi.OnBefore。这是我的想法的简化表示:

Call_VirtualMethod(method1) -> OnBefore_fires_1 -> CreateThread_and_InvokeAgain -> OnBefore_fires_2 -> DoInvoke := true(即直接执行方法)

解释:

  1. 最初 SomeFlag 的值为 PostponeExecution。

  2. 第一次调用 ttc.method1 会触发 OnBefore 事件 (OnBefore_fires_1)。该方法不会执行,因为 SomeFlag 是 推迟执行。因此将创建一个线程,该线程将设置 SomeFlag 到 DirectExecute 并将再次调用相同的方法,但是 在线程的上下文中。

  3. 然后 OnBefore 再次触发(因为 Instance 是代理对象 即该方法是钩子方法)。这次 SomeFlag 是 DirectExecute 和方法将被调用。

我在调用方法时使用代理对象(Instance var),因为我希望“Self”指向它。这样如果method1调用了同一个类的其他虚方法,后面的虚方法也会自动在一个线程中执行。

为此,我需要将标志存储在某处,即指示 OnBefore 的第二次调用要做什么。 我的问题是如何/在哪里存储“SomeFlag”,以便在两次调用 OnBefore 期间可以访问它? 解决方案应该是跨平台的。也欢迎提出建议/其他解决方案。

我想这可以通过 VMT 修补(link1link2link3)来完成,但 VirtualProtect 是一个仅限 Windows 的功能,因此会违反跨平台要求。

高度赞赏任何想法。

这是怎么回事:

想象一下你可以在 Delphi 中拥有这样的类:

TBusinessLogic = class
  public
    // Invokes asynchronously
    [InvokeType(Async)]
    procedure QueryDataBase;

    // Invokes asynchronously and automatically return asocciated ITask (via OnBefore event)
    [InvokeType(Await)]
    function DownloadFile(AUrl: string): ITask;

    // This method touches GUI i.e. synchonized
    [InvokeType(VclSend)]
    procedure UpdateProgressBar(AValue: integer);

    // Update GUI via TThread.Queue
    [InvokeType(VclPost)]
    procedure AddTreeviewItem(AText: string);

end;

...

procedure TBusinessLogic.QueryDataBase;
begin
  // QueryDataBase is executed ASYNC (QueryDataBase is tagged as Async)
  // Do heavy DB Query here

  // Updating GUI is easy, because AddTreeviewItem is tagged as VclPost
  for SQLRec in SQLRecords do
    AddTreeviewItem(SQLRec.FieldByName["CustomerName"].asString);
end;

这种方法确实简化了线程和同步。不再需要 Ducktyping TThread.Synchronize()、TThread.Queue() 等。 您只需关注业务逻辑并调用适当的方法 - OnBefore 事件为您完成“脏”工作。非常接近 C# 中的 Await 方法。

这是主要思想!

更新: 我重新编辑了整个问题以使其更加清晰。

【问题讨论】:

  • 为什么不将PostponeExecution 参数添加到您的InvokeMethod 并默认设置为True,然后在匿名方法中使用False 调用它?
  • @StefanGlienke 我无法修改 InvokeMethod 的签名。我的意思是我为我的问题准备了一个缩小的展示。 InvokeMethod 属于系统类,有其他名称。
  • 您不能更改签名但可以更改其实现?那么然后将实现移动到带有附加参数的另一个方法并从原始方法调用它。我不明白为什么要求会决定实施。无论如何,将调用状态存储到方法或对象实例是错误的,不应该这样做。
  • @StefanGlienke 实际上 InvokeMethod 是在特定事件上调用的匿名方法。所以事件本身被调用了两次。而且我现在看到这个例子并不精确......稍后我会更正一下。
  • 我的问题是你为什么需要这样做?由于缺乏以这种方式工作的某些要求,这听起来像是一大堆技术债务的开始。

标签: multithreading delphi rtti method-invocation


【解决方案1】:

你的方法是错误的。您尝试做的基本上是调用虚拟方法,但无需再次通过拦截器。由于拦截器本身已经在 VMT 中注册了存根,通过 invoke 调用该方法将再次命中拦截器存根,从而导致递归。

我过去在 Spring4D 拦截中通过使用Rtti.Invoke 例程在较低级别进行调用来完成此操作。

这就是你的做法:

procedure DirectlyInvokeMethod(Instance: TObject; Method: TRttiMethod;
  const Args: TArray<TValue>);
var
  params: TArray<TRttiParameter>;
  values: TArray<TValue>;
  i: Integer;
begin
  params := Method.GetParameters;
  SetLength(values, Length(Args) + 1);
  values[0] := Instance;

  // convert arguments for Invoke call (like done in the DispatchInvoke methods
  for i := Low(Args) to High(Args) do
    PassArg(params[i], args[i], values[i + 1], Method.CallingConvention); // look at Rtti.pas for PassArg

  Rtti.Invoke(Method.CodeAddress, values, Method.CallingConvention, nil);
end;

由于您是异步调用此函数,因此我没有处理函数 - 否则您必须检查方法的 ReturnType 以传递正确的句柄,这里我们只是传递 nil。

对于 PassArg 例程,请查看 System.Rtt.pas。

那你就这样称呼它:

vmi.OnBefore :=
  procedure(Instance: TObject; Method: TRttiMethod;
    const Args: TArray<TValue>; out DoInvoke: Boolean;
      out Result: TValue)
  begin
    DoInvoke := Method.Parent.Handle = TObject.ClassInfo; // this makes sure you are not intercepting any TObject virtual methods
    if not DoInvoke then // otherwise call asynchronously
      TThread.CreateAnonymousThread(
        procedure
        begin
          DirectlyInvokeMethod(Instance, Method, Args);
        end).Start;
  end;

请记住,出于显而易见的原因,任何 var 或 out 参数都不适合这种方法。

【讨论】:

  • 显然我不知道 Rtti.Invoke 会绕过拦截器存根:) 我稍后再试。谢谢!
  • 不应该将Instance var作为第一个参数传递给DirectlyInvokeMethod吗? Rtti.Invoke 也应该接收值数组而不是 args?
猜你喜欢
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 2020-07-24
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多