Look at a non-multithreaded example, other operations can not be performed (such as form drag) when the code is executed:
{ Custom method: drawing on the form ... } Procedure MyMethod; var I: Integer; the begin for I: = 0 to 500000 do the begin Form1.Canvas.Lock; Form1.Canvas.TextOut ( 10 , 10 , the IntToStr ( I)); Form1.Canvas.Unlock; End ; End ; { calling custom method above } Procedure TForm1.Button1Click (Sender: TObject); the begin MyMethod; End ;
Amended as multithreading (modify only one line of code):
procedure MyMethod; var i: Integer; begin for i := 0 to 500000 do begin Form1.Canvas.Lock; Form1.Canvas.TextOut(10, 10, IntToStr(i)); Form1.Canvas.Unlock; end; end; procedure TForm1.Button1Click(Sender: TObject); begin TThread.CreateAnonymousThread(MyMethod).Start; //!!! end;
Code analysis:
1, TThread now adds a lot of class method (direct method by the class name called), TThread.CreateAnonymousThread () is a more useful.
2, as the name suggests, CreateAnonymousThread is to establish an anonymous thread object, its argument is that we need a method executed in a thread
3, but the thread is suspended CreateAnonymousThread established, it needs to manually run; the Start the latter method is used to wake up the thread.
4, (formerly) wake up threads or a method may be used Resume suspended properties (Suspended: = False;); but they are about to be abandoned, should now use start to start the thread.
The parameter type is CreateAnonymousThread TProc anonymous methods (reference), so the code can be abbreviated as:
Procedure TForm1.Button1Click (Sender: TObject); the begin TThread.CreateAnonymousThread ( // direct write method body Procedure var I: Integer; the begin for I: = 0 to 500000 do the begin Canvas.Lock; Canvas.TextOut ( 10 , 10 , the IntToStr (I)); Canvas.Unlock; End ; End // here no semicolon ) .Start; End ;
Delay Execution:
var myThread: TThread; procedure TForm1.FormCreate(Sender: TObject); begin myThread := TThread.CreateAnonymousThread( procedure var i: Integer; begin for i := 0 to 500000 do begin Canvas.Lock; Canvas.TextOut(10, 10, IntToStr(i)); Canvas.Unlock; end; end ); end; procedure TForm1.Button1Click(Sender: TObject); begin myThread.Start; end;