-
دوستان لطفا از تمامي مباحث ذكر شده در بالا نمونه سورس قرار بديد .
-
سلام.
پیشنهاد (در تحقیقات) من استفاده از Component JvThread هست که در مجموعه JCL+JVC وجود داره .
مثالش هم همراهشه.
اینم یه سورس که دلیل استفاده از Thraed ها رو میگه:
کد:
unit BackTaskForm;
interface
uses
SysUtils, Types, Classes, Variants, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ProgressBar1: TProgressBar;
Button2: TButton;
Button3: TButton;
LBox1: TListBox;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{function local to the unit}
function IsPrime (N: Integer): Boolean;
var
Test: Integer;
begin
IsPrime := True;
for Test := 2 to N - 1 do
if (N mod Test) = 0 then
begin
IsPrime := False;
break; {jump out of the for loop}
end;
end;
const
Max = 100000;
procedure TForm1.Button1Click(Sender: TObject); // Plain
var
I, Tot: Integer;
begin
Tot := 0;
for I := 1 to Max do
begin
if IsPrime (I) then
Begin
Tot := Tot + I;
LBox1.Items.Add(IntToStr(i))
End;
ProgressBar1.Position := I * 100 div Max;
end;
ShowMessage ('Plain-> '+IntToStr (Tot));
end;
procedure TForm1.Button2Click(Sender: TObject); // App.ProcMsg
var
I, Tot: Integer;
begin
Tot := 0;
for I := 1 to Max do
begin
Begin
Tot := Tot + I;
LBox1.Items.Add(IntToStr(i))
End;
ProgressBar1.Position := I * 100 div Max;
Application.ProcessMessages;
end;
ShowMessage ('App.ProcMsg -> '+IntToStr (Tot));
end;
// custom thread class
type
TPrimeAdder = class(TThread)
private
FMax, FTotal,FCurrent, FPosition: Integer;
protected
procedure Execute; override;
procedure ShowTotal;
procedure UpdateProgress;
procedure UpdateListBox;
public
property Max: Integer read FMax write FMax;
end;
procedure TPrimeAdder.Execute;
var
I, Tot: Integer;
begin
Tot := 0;
for I := 1 to FMax do
begin
Begin
Tot := Tot + I;
FCurrent:=i;
Synchronize(UpdateListBox);
End;
if I mod (fMax div 100) = 0 then
begin
FPosition := I * 100 div fMax;
Synchronize(UpdateProgress);
end;
end;
FTotal := Tot;
Synchronize(ShowTotal);
end;
procedure TPrimeAdder.ShowTotal;
begin
ShowMessage ('Thread: ' + IntToStr (FTotal));
end;
procedure TForm1.Button3Click(Sender: TObject); //Thread
var
AdderThread: TPrimeAdder;
begin
AdderThread := TPrimeAdder.Create (True);
AdderThread.Max := Max;
AdderThread.FreeOnTerminate := True;
AdderThread.Priority:=tpHigher;
AdderThread.Resume;
end;
procedure TPrimeAdder.UpdateProgress;
begin
Form1.ProgressBar1.Position := fPosition;
end;
procedure TPrimeAdder.UpdateListBox;
begin
Form1.LBox1.Items.Add( IntToStr(FCurrent) );
end;
end.
با تشکر از فرهاد
موفق و پیروز باشی.