Send string data from Thread to main form

前端 未结 3 1571
灰色年华
灰色年华 2020-12-29 14:03

In Dephi, I create a thread, like this, which will send message to main form from time to time

Procedure TMyThread.SendLog(I: Integer);
Var
  Log: array[0..2         


        
3条回答
  •  囚心锁ツ
    2020-12-29 14:32

    If you have D2009 or later version, there is another way to post messages to your main form. TThread.Queue is an asynchronous call from a thread, where a method or procedure can be executed in the main thread.

    The advantage here is that the frame to set up the message passing is less complex. Just pass your callback method when creating your thread. No handles and no explicit handling of string allocation/deallocation.

    Type
      TMyCallback = procedure(const s : String) of object;
    
      TMyThread = class(TThread)
        private
          FCallback : TMyCallback;
          procedure Execute; override;
          procedure SendLog(I: Integer);
        public
          constructor Create(aCallback : TMyCallback);
      end;
    
    constructor TMyThread.Create(aCallback: TMyCallback);
    begin
      inherited Create(false);
      FCallback := aCallback;
    end;
    
    procedure TMyThread.SendLog(I: Integer);
    begin
      if not Assigned(FCallback) then
        Exit;
      Self.Queue(  // Executed later in the main thread
        procedure
        begin
          FCallback( 'Log: current stag is ' + IntToStr(I));
        end
      );
    end;
    
    procedure TMyThread.Execute;
    var
      I: Integer;
    begin
      for I := 0 to 1024 * 65536 do
      begin
        if ((I mod 65536) = 0) then
        begin
          SendLog(I);
        End;
      End;
    end;
    

    procedure TMyForm.TheCallback(const msg : String);
    begin
      // Show msg
    end;
    
    procedure TMyForm.StartBackgroundTask(Sender : TObject);
    begin
      ... 
      FMyThread := TMyThread.Create(TheCallback);
      ...
    end;
    

提交回复
热议问题