定义线程的方法(20分)

  • 主题发起人 主题发起人 guaiguai
  • 开始时间 开始时间
G

guaiguai

Unregistered / Unconfirmed
GUEST, unregistred user!
在看书上的例子的时候,由于书上写的不是很详细,所以没搞清楚一个问题:如何定义线程
我试过了,原来在主窗体下就有一个type,但将定义线程的代码写进去后报错.但我自己再新写一和type定义(以及此后的private,public)但好象还是有问题
请问我应该怎么做?
 
不知道你是怎么定义的。代码呢?
 
给你一个完整的例子,看看:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBTables, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, Db;

type
TForm1 = class(TForm)
Query1: TQuery;
DBGrid1: TDBGrid;
Panel1: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
se1: TSession;
Database1: TDatabase;
DataSource1: TDataSource;
BitBtn4: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

TQueryThread=class(TThread)
private
FQuery: TQuery;
FDataSource: TDataSource;
procedure ConnectDataSource;
protected
procedure Execute; override;
public
constructor Create(Query: TQuery;
DataSource: TDataSource); virtual;
end;
var
Form1: TForm1;
Q1, { 线程查询对象1 }
Q2: TQueryThread; { 线程查询对象2 }
implementation

{$R *.DFM}

{ TQueryThread }

procedure TQueryThread.ConnectDataSource;
begin
FDataSource.DataSet := FQuery;{ 该方法在查询结束后才调用 }
end;

constructor TQueryThread.Create(Query: TQuery; DataSource: TDataSource);
begin
FQuery := Query;
FDataSource := DataSource;
inherited Create(True);
FreeOnTerminate := False;
end;

procedure TQueryThread.Execute;
begin
try
FQuery.Open; { 打开查询 }
Synchronize(ConnectDataSource);{ 线程同步 }
except
ShowMessage('Query Error'); { 线程异常 }
end;
end;

procedure TForm1.BitBtn1Click(Sender: TObject);
begin
if Q1.Suspended then
begin
Q1.Resume;
(Sender as TBItBtn).Caption:='Suspend'
end
else begin
Q1.Suspend;
(Sender as TBItBtn).Caption:='Resume'
end
end;

procedure TForm1.BitBtn4Click(Sender: TObject);
begin
query1.close;
Q1:=TQueryThread.Create(Query1,DataSource1);
end;

procedure TForm1.BitBtn2Click(Sender: TObject);
begin
Q1.Terminate;
Q1.Destroy;
end;

end.
 
后退
顶部