传递参数以同步过程调用 [英] Pass parameters to Synchronize procedure call

查看:166
本文介绍了传递参数以同步过程调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建线程对象时,我想从需要同步的应用程序调用代码。问题是,我不知道如何调用同步使用参数的应用程序函数

When creating a thread object, I want to call code from the application that needs to be synchronized. The problem is that I don't know how to call Synchronize for an application function with parameters.

说我们有

procedure ThreadObject.Execute;
var
  val1,val2:integer;
  Star:string;
begin
  Synchronize(funcyfunc); //how to pass val1,val2,star here?
end;

其中 funcyfunc 定义如下



where funcyfunc is defined as follow

procedure OtherClass.funcyfunc(param1,param2:integer;spok:string);
begin
   letsCallFriends(spok,param1);
   letsCallFriends(spok,param2);
end;

现在,奇怪的解决方法就是在ThreadObject私有的

now the odd solution to this would be to say in ThreadObject private

private
  star:string;
  val1,val2:integer;
  procedure starVal;

在实现中我们做了

procedure ThreadObject.starVal;
begin
  funcyfunc(Star,val1,val2);
end;

在线程执行我们更改为

procedure ThreadObject.Execute;
var
  val1,val2:integer;
  Star:string;
begin
  Synchronize(starVal); //how to pass val1,val2,star here?
end;

但这是一个麻烦,因为每个过程调用必须有一个全局变量。有更好的方法吗?

but this is a hassle, as for each procedure call there must be a global variable. Is there a better way?

代码:

unit ThreadObject;

interface

uses
  Classes;

type
  TThreadObject= class(TThread)
  private
    star:string;
    val1,val2:integer;
    procedure starVal;
  protected
    procedure Execute; override;

    //assume we have a constructor that ini the star val1 val2.
  end;

implementation

{ TThreadObject }

procedure ThreadObject.Execute;
var
  val1,val2:integer;
  Star:string;
begin
  Synchronize(starVal); //how to pass val1,val2,star here?
end;

procedure ThreadObject.starVal;
begin
  funcyfunc(Star,val1,val2);
end;

end.


推荐答案

使用匿名方法。

您可以在手册中阅读TThread.Synchronize

As you can read in the manual for the TThread.Synchronize

Synchronize(
  procedure
  begin
    Form1.Memo1.Lines.Add('Begin Execution');
  end);

在上面的示例中,引用的变量 Form1 将被复制和保存,直到执行的过程(称为变量捕获)。

In the example above the referenced variable Form1 would be copied and saved until the procedures executed (that is called variable capture).

你的匿名过程应该使用你的变量var1和var2,并且它们被捕获

You anonymous procedure should use your variables var1 and var2 and they be captured too

http:/ /docwiki.embarcadero.com/Libraries/XE5/en/System.Classes.TThread.Synchronize

这篇关于传递参数以同步过程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆