新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