转载自:https://www.cnblogs.com/lackey/p/6296414.html
unit Unit10; interface uses Winapi . Windows, Winapi . Messages, System . SysUtils, System . Variants, System . Classes, Graphics, Vcl . Controls, Vcl . Forms, Vcl . Dialogs, uAccumulation, Vcl . StdCtrls; type TForm10 = class (TForm) Edit1: TEdit; Button1: TButton; procedure Button1Click(Sender: TObject); private procedure OnAccumulated(Sender: TAccumulationThread); end ; implementation { $R *.dfm} procedure TForm10 . Button1Click(Sender: TObject); var accThread: TAccumulationThread; begin accThread := TAccumulationThread . Create( true ); accThread . OnAccumulated := self . OnAccumulated; //指定事件。 accThread . FreeOnTerminate := true ; // 线程结束后自动释放 accThread . Num := 100 ; accThread . Start; end ; procedure TForm10 . OnAccumulated(Sender: TAccumulationThread); begin // 这里是线程时空 // 要更新 UI ,要用 Synchorinize 把更新的操作 // 塞到主线程时空里去运行。注意理解:“塞!” TThread . Synchronize( nil , procedure begin // 这里的代码被塞到主线程时空里去了。 Edit1 . Text := inttostr(Sender . Total); end ); // Synchronize 第一个参数是 nil // 第二个参数是一个匿名函数 什么是匿名函数? 以后会介绍到。 end ; end . |
unit uAccumulation; interface uses Classes; type TAccumulationThread = class; //此为提前申明 TOnAccumulated = procedure(Sender: TAccumulationThread) of object; // 如果不提前申明,Sender 就要定义成 TObject // 在事件函数中,要操作 Sender 就需要强制转换 TAccumulationThread = class(TThread) protected procedure Execute; override; public Num: integer; Total: integer; OnAccumulated: TOnAccumulated; end; implementation procedure TAccumulationThread.Execute; var i: integer; begin Total := 0; if Num > 0 then begin for i := 1 to Num do Total := Total + i end; // 当计算完成后,就调用 OnAccumulated 通知调用者 if Assigned(OnAccumulated) then OnAccumulated(self); end; end.
原文:https://www.cnblogs.com/approx/p/11852138.html