unit UpdateDataThread;
interface
uses
Sysutils, Forms, Controls, Windows, classes,StrUtils,FileCtrl,IniFiles,ExtCtrls,ShellAPI,DB,
ADODB, ComObj,Activex,Messages, ComCtrls, DBTables, Syncobjs;
type
TWorker=class
private
datas:TStringList;
Event:TSimpleEvent;
Lock:TCriticalSection;
public
procedure add(sql:String);
function get:String;
function wait(timeout
WORD):TWaitResult;
Constructor Create;
Destructor Destroy;override;
end;
TUpdateThread = class(TThread)
private
connectionString:String;
Worker:TWorker;
procedure Runs(query:TADOQuery);
protected
procedure Execute;
override;
public
Constructor Create(connectionString:String;
Worker:TWorker);
end;
var
QUeryThread: TUpdateThread;
implementation
{ UpdateThread }
//功能:线程类的构造器
constructor TUpdateThread.create(connectionString:String;
Worker:TWorker);
begin
inherited Create(true);
self.connectionString:=connectionString;
self.Worker:=Worker;
FreeOnTerminate := True;
Resume;
end;
//功能:执行线程的方法
//说明:每个线程创建单独的数据连接
procedure TUpdateThread.Execute;
var
aUpdateQry :TADOQuery;
MyConnet:TADOConnection;
abegin
Id,aCheckComId:integer;
aIndexbegin
:integer;
aGetComStr:string;
begin
//使用com对象必须要初始化
CoInitialize(nil);
try
MyConnet:= TADOConnection.Create(nil);
aUpdateQry:=TADOQuery.Create(nil);
try
aUpdateQry.Connection:=MyConnet;
MyConnet.ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;Data Source='+self.connectionString;
MyConnet.LoginPrompt :=false;
MyConnet.Open;
except
exit;
end;
while not Terminateddo
begin
self.Runs(aUpdateQry);
sleep(10);
end;
finally
aUpdateQry.Free;
MyConnet.Free;
CoUninitialize;
//必须使用
end;
end;
procedure TUpdateThread.Runs(query:TADOQuery);
var
aSetStr:string;
begin
self.Worker.wait(INFINITE);
aSetStr:=self.Worker.get;
if aSetStr<>'' then
begin
with querydo
begin
Close;
SQL.Clear;
SQL.Add(aSetStr);
try
ExecSQL;
except
end;
end;
end;
end;
{ TWorker }
procedure TWorker.add(sql: String);
begin
Lock.Acquire;
try
datas.Add(sql);
Event.SetEvent;
finally
Lock.Release;
end;
end;
constructor TWorker.Create;
begin
datas:=TStringList.Create;
Event:=TSimpleEvent.Create;
Lock:=TCriticalSection.Create;
end;
destructor TWorker.Destroy;
begin
Lock.Free;
Event.Free;
datas.Free;
inherited;
end;
function TWorker.get: String;
begin
Lock.Acquire;
try
Result:='';
if datas.Count>0 then
begin
result:=datas.Strings[0];
datas.Delete(0);
end
else
begin
Event.ResetEvent;
end;
finally
Lock.Release;
end;
end;
function TWorker.wait(timeout: DWORD):TWaitResult;
begin
Result:=Event.WaitFor(timeout);
end;
end.