如何管理线程的返回值? [英] How to manage the return value of a thread?

查看:76
本文介绍了如何管理线程的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个派生自 TThread 的类,它在后台执行查询。

I created a class derived from TThread that executes in background a query.

我想要这个类与客户端解耦。

I want that this class is decoupled from the client.

这种线程的目的是执行一个简单的检查(像当前连接到应用程序的用户数量没有阻塞UI) ,所以一个简单的想法是使用Synchronize方法。

This kind of thread has the purpose of executing a simple check (like how many users are currently connected to the application, without blocking the UI), so a simple idea is to use the Synchronize Method.

无论如何,我希望它被解耦,我传递一个类型为

Anyway since i want it to be decoupled i pass in the constructor a parameter of type

TSyncMethod: procedure of object;

其中 TSyncMethod 是客户端上的一种方法(在我的情况下的一种形式)。

Where TSyncMethod is a method on the client (a form in my case).

无论如何我可以将值传递给TSyncMethod?我应该在一些全球地方上写出结果,然后在我的TSyncMethod内检查一下?

Anyway how can I pass the value to TSyncMethod? I should write the result on some "global place" and then inside my TSyncMethod I check for it?

我也试着想到

TSyncMethod: procedure(ReturnValue: integer) of object;

但是当我调用 Synchronize(MySyncMethod)我不能传递参数。

but of course when I call Synchronize(MySyncMethod) I cannot pass parameters to it.

推荐答案

对于这样一个简单的例子,您可以将所需的值放入成员字段的线程(或甚至进入线程自己的 ReturnValue 属性),然后使用中间线程方法Synchronize()执行回调,然后可以将该值传递给回电话。例如:

For such a simply example, you can put the desired value into a member field of the thread (or even into the thread's own ReturnValue property), then Synchronize() execution of the callback using an intermediate thread method, where you can then pass the value to the callback. For example:

type
  TSyncMethod: procedure(ReturnValue: integer) of object;

  TQueryUserConnected = class(TThread)
  private
    FMethod: TSyncMethod;
    FMethodValue: Integer;
    procedure DoSync;
  protected
    procedure Execute; override;
  public
    constructor Create(AMethod: TSyncMethod); reintroduce;
  end;

constructor TQueryUserConnected.Create(AMethod: TSyncMethod);
begin
  FMethod := AMethod;
  inherited Create(False);
end;

procedure TQueryUserConnected.Execute;
begin
  ...
  FMethodValue := ...;
  if FMethod <> nil then
    Synchronize(DoSync);
end;

procedure TQueryUserConnected.DoSync;
begin
  if FMethod <> nil then
    FMethod(FMethodValue);
end;

这篇关于如何管理线程的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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