Delphiスレッドにパラメータを渡すには?
Delphiでスレッドにパラメーターを渡す方法は次のとおりです。
- スレッドのコンストラクタで引数を渡す:スレッドオブジェクトを作成するときに、コンストラクタに直接引数を渡すことができます。例えば:
type
TMyThread = class(TThread)
private
FParam: Integer;
protected
procedure Execute; override;
public
constructor Create(Param: Integer);
end;
constructor TMyThread.Create(Param: Integer);
begin
inherited Create(True);
FParam := Param;
end;
procedure TMyThread.Execute;
begin
// 使用 FParam 进行操作
end;
そのために、以下ようにスレッドを作成して実行することができます。
var
MyThread: TMyThread;
begin
MyThread := TMyThread.Create(123);
MyThread.Start;
end;
- スレッドの属性を用いたパラメータの渡し方:スレッドオブジェクト生成後にスレッドの属性を設定することで、自分自身の引数を通すことができます。例:
type
TMyThread = class(TThread)
private
FParam: Integer;
protected
procedure Execute; override;
public
property Param: Integer read FParam write FParam;
end;
procedure TMyThread.Execute;
begin
// 使用 FParam 进行操作
end;
スレッドは以下のようにして作成、実行できます。
var
MyThread: TMyThread;
begin
MyThread := TMyThread.Create(True);
MyThread.Param := 123;
MyThread.Start;
end;
- パラメーター化したコンストラクターを使用してパラメーターを渡す: Delphi 10.4 以降では、パラメーター化したコンストラクターを使用してパラメーターを渡すことができます。たとえば:
type
TMyThread = class(TThread)
private
FParam: Integer;
protected
procedure Execute; override;
public
constructor Create(Param: Integer);
end;
constructor TMyThread.Create(Param: Integer);
begin
inherited Create(True);
FParam := Param;
end;
procedure TMyThread.Execute;
begin
// 使用 FParam 进行操作
end;
そのあと,下記のようにスレッドを作成して実行できます:
var
MyThread: TMyThread;
begin
MyThread := TMyThread.Create(123);
MyThread.Start;
end;
ディルフィスレッドにパラメータを渡す一般的な方法は上で説明しました。具体的なニーズに基づいて適切な方法を選択してください。