多线程 – 如何管理线程的返回值?

前端之家收集整理的这篇文章主要介绍了多线程 – 如何管理线程的返回值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个派生自TThread的类,在后台执行查询.

我希望这个类与客户端分离.@H_403_3@

这种线程的目的是执行一个简单的检查(像当前连接到应用程序的用户数量,而不会阻塞UI),所以一个简单的想法是使用同步方法.@H_403_3@

无论如何,因为我想要它去耦合,我传递一个类型的参数的构造函数@H_403_3@

TSyncMethod: procedure of object;

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

无论如何我可以将值传递给TSyncMethod?我应该把结果写在一些“全球的地方”,然后在我的TSyncMethod里面我检查一下?@H_403_3@

我也试过想到@H_403_3@

TSyncMethod: procedure(ReturnValue: integer) of object;

当然当我打电话给Synchronize(MySyncMethod)时,我无法传递参数.@H_403_3@

解决方法

对于这样一个简单的例子,您可以将所需的值放入线程的成员字段(或甚至到线程自己的ReturnValue属性),然后使用中间线程方法执行回调,然后可以将其传递给回调的值.例如:
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;
原文链接:https://www.f2er.com/java/123617.html

猜你在找的Java相关文章