Search code examples
multithreadingdelphireturn-valuedelphi-xe6

Return String from Thread Delphi


I'm using Delphi XE6.

I have a thread where I pass a ID and would like to get back a string created by the thread. I looked at all examples, but they all getting values back when thread is running I just need it OnTerminate.

Calling the thread from a form:

StringReturnedFromThread := PrintThread.Create(MacId);

PrintThread = class(TThread)
  private        
    MyReturnStr, PrinterMacId : String;
  public
        constructor Create(MacId: String); reintroduce;
        procedure OnThreadTerminate(Sender: TObject);
  protected
    procedure Execute; override;
  end;

constructor PrintThread.Create(MacId: String);
begin
    inherited Create(False);
    OnTerminate := OnThreadTerminate;
    FreeOnTerminate := True;
    PrinterMacId := MacId;
end;

procedure PrintThread.Execute;
begin
    PrepareConnection;
    MyReturnStr:= RequestPrintJobs(PrinterMacId);
end;

procedure PrintThread.OnThreadTerminate(Sender: TObject);
begin


end;

Thanks for any help.


Solution

  • You need to intercept thread termination. One way is to use TThread.OnTerminate event/callback.

    Below a sample code.

    Thread unit:

    unit Processes;
    
    interface
    
    uses
      System.Classes;
    
    type
      TProcess = class(TThread)
      private
        FReturnStr: string;
        FMacId: string;
      protected
        procedure Execute; override;
      public
        property MacId: string read FMacId write FMacId;
        property ReturnStr: string read FReturnStr write FReturnStr;
        constructor Create;
      end;
    
    implementation
    
    constructor TProcess.Create;
    begin
      inherited Create(True);
      FreeOnTerminate := True;
    end;
    
    procedure TProcess.Execute;
    begin
      // Some hard calculation here
      FReturnStr := FMacId + 'BLA';
    end;
    
    end.
    

    Thread usage:

    uses Processes;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var P: TProcess;
    begin
      // Create the thread
      P := TProcess.Create;
      // Initialize it
      P.MacId := 'MID123';
      // Callback handler
      P.OnTerminate := OnProcessTerminate;
      // Let's go
      P.Start;
    end;
    
    procedure TForm1.OnProcessTerminate(Sender: TObject);
    var P: TProcess;
    begin
      // The thread has been terminated
      P := TProcess(Sender);
      ShowMessage(P.ReturnStr);
    end;
    

    The thread will return MID123BLA on it's termination.