Multithreading – how do I manage the return values of threads?

I created a class derived from TThread to execute queries in the background

I want this class to be separate from the client

The purpose of this thread is to perform a simple check (such as the number of users currently connected to the application without blocking the UI), so a simple idea is to use the synchronization method

Anyway, because I want it decoupled, I pass a constructor of type parameters

TSyncMethod: procedure of object;

Tsyncmethod is a method on the client (in my case, a form)

Can I pass the value to tsyncmethod anyway? Should I write the results in some "global places" and then check them in my tsyncmethod?

I tried to think of it

TSyncMethod: procedure(ReturnValue: integer) of object;

Of course, when I call synchronize (mysyncmethod), I can't pass parameters

Solution

For such a simple example, you can put the required value into the thread's member field (or even to the thread's own returnValue property), then use the intermediate thread method to execute the callback, and then pass it to the callback value 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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>