溫馨提示×

delphi線程傳遞參數(shù)的方法是什么

小億
144
2023-10-26 20:56:01
欄目: 編程語言

在Delphi中,可以通過以下方法傳遞參數(shù)給線程:

  1. 使用構(gòu)造函數(shù):可以在線程的構(gòu)造函數(shù)中添加參數(shù),然后在創(chuàng)建線程時(shí)傳遞參數(shù)。例如:
type
  TMyThread = class(TThread)
  private
    FParam: Integer;
  public
    constructor Create(Param: Integer);
    procedure Execute; override;
  end;

constructor TMyThread.Create(Param: Integer);
begin
  inherited Create(True);
  FParam := Param;
end;

procedure TMyThread.Execute;
begin
  // 使用 FParam 做一些操作
end;

// 創(chuàng)建線程并傳遞參數(shù)
var
  MyThread: TMyThread;
begin
  MyThread := TMyThread.Create(123);
  MyThread.Start;
end;
  1. 使用屬性:可以在線程中添加一些公共屬性,然后在創(chuàng)建線程后設(shè)置屬性的值。例如:
type
  TMyThread = class(TThread)
  private
    FParam: Integer;
  public
    property Param: Integer read FParam write FParam;
    procedure Execute; override;
  end;

procedure TMyThread.Execute;
begin
  // 使用 Param 做一些操作
end;

// 創(chuàng)建線程并設(shè)置參數(shù)
var
  MyThread: TMyThread;
begin
  MyThread := TMyThread.Create(True);
  MyThread.Param := 123;
  MyThread.Start;
end;

這兩種方法都可以用來傳遞參數(shù)給線程,在線程的 Execute 方法中可以使用傳遞的參數(shù)進(jìn)行操作。

0