扩展 delphi 线程 使之传递参数.(给匿名线程增加参数)


本文整理自网络,侵删。

 
新delphi的线程TThread有了CreateAnonymousThread方法,如果再为它加一个可传递的参数不就更好了吗?代码如下:

复制代码
复制代码
  TAnonymousThreadX<T> = class(TThread)
  private
    FProc: TProc<T>;
    AValue:T;
  protected
    procedure Execute; override;
  public
    constructor Create(const AProc: TProc<T>;ProcPar:T);
  end;

  TThreadHelper= class helper for TThread
    public
      class function CreateAnonymousThreadX<T>(const ThreadProc: TProc<T>;proPar:T): TThread; static;
  end;

implementation

{ TAnonymousThreadX }

constructor TAnonymousThreadX<T>.Create(const AProc: TProc<T>;ProcPar:T);
begin
  inherited Create(True);
  FreeOnTerminate := True;
  FProc := AProc;
  Avalue:=ProcPar;
end;

procedure TAnonymousThreadX<T>.Execute;
begin
  inherited;
  FProc(Avalue);
end;

{ TThreadHelper }

class function TThreadHelper.CreateAnonymousThreadX<T>(const ThreadProc: TProc<T>; proPar: T): TThread;
begin
  Result := TAnonymousThreadX<T>.Create(ThreadProc,proPar);
end;
复制代码
复制代码
代码挺简单的,就是传递了一个方法及参数. 在线程里调用就是了.

将以上代码保存在一个单元中,引用了之后,就可以这样用了:

复制代码
复制代码
//这样使用
TThread.CreateAnonymousThreadX<Integer>(TestX,1234).Start;

//这是TestX方法体
procedure T***.TestX(Avalue: Integer);
begin
  btnContinue.Caption:=IntToStr(Avalue);
end;


//如果不想定义TestX方法,也可以如下方法直接调用
  TThread.CreateAnonymousThreadX<Integer>(
  procedure(Avalue:Integer)
  begin
    btnContinue.Caption:=IntToStr(Avalue);
  end
  ,12345).Start;
复制代码
复制代码
如果执行线程的方法有两个,三个参数,对照着改就是了.

这样用线程是不是更简单一些了呢.

http://www.cnblogs.com/ttgss/p/3334723.html

相关阅读 >>

Delphi 图像识别技术(逐行扫描识别)

Delphi : tstringlist的find,indexof和sort

Delphi 控制台关闭指定窗口

Delphi 7 中dbgrid的排序

Delphi 数字签名添加器源码

Delphi xe7的android应用取得wi-fi的信息

Delphi实现变速齿轮

Delphi 动态修改显示器分辨率

Delphi 金木水火土 生克用法

Delphi richedit 的scrollbar自动向下滚动

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...