Quantcast
Channel: Piece Of Code » Code snippets
Viewing all articles
Browse latest Browse all 10

Delphi: XE2 threading

$
0
0

This is demo write number in memo using thread. in this case we use Delphi xe 2. We give name the thread with WriteThread, Ok, lets create new application, put one tmemo, and two buttons.

click button1 and change the caption on window properties become Start ,and button2 become Stop

you can see picture below :
threaddesign

look this code :

 

private
    { Private declarations }
  public
    { Public declarations }
  end;

  type
  WriteThread = class(TThread)
  private
     i:byte;
    protected
    procedure Execute; override;
    procedure DoSomething;
  end;

var
  Form1: TForm1;
  writememo:WriteThread;

the next step is create the implementation of thread :

implementation

{$R *.dfm}

procedure WriteThread.Execute;
begin
 while not Terminated do
   begin
     inc(i);
     form1.Memo1.Lines.Add(inttostr(i));
     Synchronize(DoSomething);
   end;
end;

procedure WriteThread.DoSomething;
begin
 if i > 10 then i:=0;
end;

 

now we call the thread in button1onclick.

procedure TForm1.Button1Click(Sender: TObject);
 begin
 writememo:=WriteThread.Create;
 end;

so if we click button1 the writememo will start to write number in memo1.
threadrun
the thread will stop until we click botton2, how to stop thread..?

procedure TForm1.Button2Click(Sender: TObject);
begin
writememo.Terminate;
end;


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images